Camel异常处理策略

异常策略

异常策略主要用来拦截和处理特定的异常。

假设有如下异常:

org.apache.camel.RuntimeCamelException (wrapper by Camel)
+ com.mycompany.OrderFailedException
  + java.net.ConnectException

真正的异常是ConnectException,但是它被包装成了OrderFailedException,然后又被包装成了 RuntimeCamelException。

Camel会按照ConnectionException -> OrderFailedException -> OrderFailedException的顺序查找最佳匹配的OnException配置。

假设存在如下OnException配置:

onException(OrderFailedException.class).maximumRedeliveries(3);

抛出RuntimeCamelException异常后,Camel会首先查看ConnectionException是否与OrderFailedException完全匹配,很明显不完全匹配;

Camel继续检查ConnectionException是否是OrderFailedException的子类,很明显也不是;

然后Camel继续查看包装类OrderFailedException是否与OrderFailedException完全匹配,这次他们完全匹配,因此会采用OrderFailedException的异常策略。

onException的配置会覆盖error handler的配置。假设error handler配置的重试次数是5,则OrderFailedException异常侧率的重试次数3将会被使用。

让我们看一下稍微复杂的情形,假设存在如下on exception 配置:

onException(OrderFailedException.class).maximumRedeliveries(3);
onException(ConnectException.class).maximumRedeliveries(10);

这次如果抛出的还是RuntimeCamelException,那么会匹配到ConnectException的异常策略,因为它跟ConnectException异常完全匹配。

如果抛出的是IOException异常,那么因为IOException与OrderFailedException不完全匹配,也不是OrderFailedException的子类;同样IOException与ConnectException不完全匹配,也不是ConnectException的子类,因此IOException不会匹配到任何异常策略。那么他会回退到error handler的配置。

Gap detection

如果Camel没有找到直接匹配的的异常策略,Camel可以利用gap detection找到Gap最小的异常策略。

假设有如下异常处理策略:

onException(ConnectException.class)
    .maximumRedeliveries(5);

onException(IOException.class)
    .maximumRedeliveries(3).redeliveryDelay(1000);

onException(Exception.class)
    .maximumRedeliveries(1).redeliveryDelay(5000);

发生如下异常:

org.apache.camel.OrderFailedException
+ java.io.FileNotFoundException

Camel首先查看是否有与FileNotFoundException完全匹配的异常策略,很明显没有;

然后Camel进行gap detection,因为FileNotFoundException是IOException和Exception的子类,因此只有这两个异常策略匹配,然后在看他们之间的Gap,IOException与FileNotFoundException之间的Gap是1, Exception与FileNotFoundException之间的Gap是2。因此IOException的异常策略是更好的选择。

java.lang.Exception
+ java.io.IOException
  + java.io.FileNotFoundException

然后Camel继续查看OrderFailedException,此时只有Exception的异常策略与之匹配,且Gap也是1。这时Exception的异常处理策略是更好的选择。

java.lang.Exception
+ OrderNotFoundException

现在有两个异常策略Gap相同,这时Camel该如何选择呢?此时Camel会选择第一个,也就是 IOException 的异常处理策略。

一个OnException配置多个异常

例子

onException(XPathException.class, TransformerException.class)
    .to("log:xml?level=WARN");
onException(IOException.class, SQLException.class, JMSException.class)
    .maximumRedeliveries(5).redeliveryDelay(3000);

核心类

org.apache.camel.processor.errorhandler.DefaultExceptionPolicyStrategy#getExceptionPolicy

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值