仅处理Camel子路径中的某些异常

时间:2015-06-16 09:47:47

标签: exception-handling apache-camel

感谢this question我知道我需要在子路由中指定errorHandler(noErrorHandler()),以便将异常传播到Camel中的父路由。但是,我想在子路由中处理一些例外,但将其余的传播给父节点。

例如:

from("direct:top")
    .onException(Exception.class)
        .log("Top-level: ${exception}")
        .continued(true)
        .end()
    .to("mock:start")
    .to("direct:sub1")
    .to("direct:sub2")
    .end();

from("direct:sub1")
    .errorHandler(noErrorHandler())
    .to("mock:sub1")
    .throwException(new IllegalArgumentException("test"));

from("direct:sub2")
    .onException(IllegalArgumentException.class)
        .log("Sub2: ${exception}")
        .continued(true)
        .end()
    // but I want all other exceptions to be propagated to the top handler
    .to("mock:sub2")
    .throwException(new IllegalArgumentException("test"))
    .throwException(new NullPointerException("test"));

sub1按预期工作,但我希望sub2在本地处理并记录IllegalArgumentException并允许NullPointerException冒泡到父级。但是,我的日志输出如下所示:

10:35:28.048 [main] INFO  route1 - Top-level: java.lang.IllegalArgumentException: test
10:35:28.049 [main] INFO  route3 - Sub2: java.lang.IllegalArgumentException: test
10:35:28.056 [main] ERROR DefaultErrorHandler - Failed delivery for (MessageId: xxxx on ExchangeId: xxx). Exhausted after delivery attempt: 1 caught: java.lang.NullPointerException: test

如果我将errorHandler(noErrorHandler())添加到sub2IllegalArgumentException会传播到父级(我不想要),并且NullPointerException根本不会被记录。有没有办法达到我想要的行为?

1 个答案:

答案 0 :(得分:0)

当你抛出一个异常时,异常是cought并且路由立即结束,所以不能抛出第二个异常。如果你想在第一个异常发生时抛出第二个异常,你应该从onException块抛出它(在.end之前)

相关问题