4

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.

P.S. 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

Ermintar
  • 1,322
  • 3
  • 22
  • 39

2 Answers2

4

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"

TacheDeChoco
  • 3,683
  • 1
  • 14
  • 17
4

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.

Claus Ibsen
  • 56,060
  • 7
  • 50
  • 65
  • Thanks, I used a similar way, by moving my route to a separate RouteBuilder implementation and removing erroorHandler there. – Ermintar Jun 18 '18 at 09:00