2.3.2. 错误处理程序
概述
errorHandler()
子句提供类似于 onException
子句的功能,但这种机制无法区分不同的异常类型。errorHandler()
子句是 Apache Camel 提供的原始异常处理机制,在实施 onException
子句之前可用。
Java DSL 示例
errorHandler()
子句在 RouteBuilder
类中定义,并应用到该 RouteBuilder
类中的所有路由。每当在一个适用的路由中出现 任何种类的 异常时,它都会触发。例如,若要定义将所有失败交换路由到 ActiveMQ deadLetter
队列的错误处理程序,您可以按照如下所示定义 RouteBuilder
:
public class MyRouteBuilder extends RouteBuilder { public void configure() { errorHandler(deadLetterChannel("activemq:deadLetter")); // The preceding error handler applies // to all of the following routes: from("activemq:orderQueue") .to("pop3://fulfillment@acme.com"); from("file:src/data?noop=true") .to("file:target/messages"); // ... } }
然而,重定向到死信频道不会发生,直到重新发送都耗尽为止。
XML DSL 示例
在 XML DSL 中,您可以使用 errorHandler
元素在 camelContext
范围内定义一个错误处理程序。例如,若要定义将所有失败交换路由到 ActiveMQ deadLetter
队列的错误处理程序,您可以按照如下所示定义 errorHandler
元素:
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:camel="http://camel.apache.org/schema/spring" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd http://camel.apache.org/schema/spring http://camel.apache.org/schema/spring/camel-spring.xsd"> <camelContext xmlns="http://camel.apache.org/schema/spring"> <errorHandler type="DeadLetterChannel" deadLetterUri="activemq:deadLetter"/> <route> <from uri="activemq:orderQueue"/> <to uri="pop3://fulfillment@acme.com"/> </route> <route> <from uri="file:src/data?noop=true"/> <to uri="file:target/messages"/> </route> </camelContext> </beans>
错误处理器的类型
表 2.1 “错误处理程序类型” 概述您可以定义的不同类型的错误处理程序。
表 2.1. 错误处理程序类型
Java DSL Builder | XML DSL 类型属性 | 描述 |
---|---|---|
|
| 将例外传播到调用者并支持重新传送策略,但它不支持死信队列。 |
|
| 支持与默认错误处理程序相同的功能,并且支持死信队列。 |
|
| 每当发生异常时,记录异常文本。 |
|
| 虚拟处理器实施,可用于禁用错误处理程序。 |
| 转换路由时出错处理程序。默认事务错误处理器实例会自动用于标记为转换的路由。 |