2

Thanks to this question I know that I need to specify errorHandler(noErrorHandler()) in a sub-route in order for exceptions to be propagated to the parent route in Camel. However I would like to handle some exceptions in the sub-route but propagate the rest to the parent.

For example:

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 works as expected, but I'd like sub2 to locally handle and log the IllegalArgumentException and allow the NullPointerException to bubble up to the parent. However, my log output looks like this:

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

If I add errorHandler(noErrorHandler()) to sub2 the IllegalArgumentException is propagated to the parent (which I don't want) and the NullPointerException isn't logged at all. Is there any way to achieve my desired behaviour?

Community
  • 1
  • 1
batwad
  • 3,588
  • 1
  • 24
  • 38

1 Answers1

0

When you throw an exception the exception is cought and route ends immediately, so the second exception can't be thrown. If you want to throw the second exception only if the first one occurs you should throw it from onException block (before .end)

dey
  • 3,022
  • 1
  • 15
  • 25
  • I've tried this, and throwing an exception in the onException block results in it being caught and logged by Camel's FatalFallbackErrorHandler rather than bubbling up as I'd like. – batwad Jul 29 '15 at 09:35
  • I think, there is default error handler in every route, so try to add between from and onException (or if this doesnt work, after onException) in subroute .errorHandler(noErrorHandler()). – dey Jul 30 '15 at 12:36