简体   繁体   中英

Camel doCatch and onException priority

I have a route with doTry() - doCatch() pair for a specific route and onException() in general.

onException(Exception.class)
    .handled(true)
    .log(LoggingLevel.ERROR, "An error occurred: ${exception.stacktrace}")
    .setBody(simple("${exception}"))
    .setHeader(Exchange.HTTP_RESPONSE_CODE, constant(500));

from("direct:mydirect")
        .routeId("myRoute")
        .doTry()
           .to("direct:internalroute")
        .doCatch(Exception.class)
            .log(LoggingLevel.ERROR, "EXCEPTION: ${exception.stacktrace}")
            .process(exceptionHandlerProcessor)
            .setHeader(Exchange.HTTP_RESPONSE_CODE, constant(500))
            .marshal(new JsonDataFormat(JsonLibrary.Jackson))
        .doFinally()
            .log("FINALLY")
        .endDoTry();

Internal route throws a plain java.lang.Exception

 throw new Exception("Catch me if you can!");

I expected the exception to be caught in doCatch() and logging and pocessing operations to be executed. However, onException() is invoked instead.

Does onException() have a higher prority? In my understanding local catch is more prioritized.

PS Removing onException() makes doCatch() invoked. However I have reasons to keep both. Camel version is: org.apache.camel:camel-cxf:2.21.0.000033-fuse-000001-redhat-1

IMHO it's not a question of priority but more a question of design/implementation. See the doc:

"The onException clause is a mechanism for trapping, rather than catching exceptions. That is, once you define an onException clause, it traps exceptions that occur at any point in a route"

When you have a doTry .. doCatch block and you call another route, such as you do via

.to("direct:internalroute")

Then you need to turn off error handling on that route, eg in

from("direct:internalroute")
  .errorHandler(noErrorHandler())

If you want all error handling to happen via the doTry .. doCatch block only.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM