Exception handling in parent router

Viewed 135

I have parent router that calls other routers. The parent router has all the exception handling logic. In all child routers, on exception, I want to just add properties in the exchange object and leave the actual exception handling in the parent(main) router.

Example:

public class ParentRouter extends RouteBuilder {
    @Override 
    public void configure() throws Exception {
        onException(CustomException.class)
            .process(new ExceptionProcessor())
            .handled(true);
         from("direct:parent-route").to("direct:child-route");

         from("direct:child-route")
             .onException(CustomException.class)
                 .process(new Processor(){
                     @Override 
                     public process(Exchange exchange){
                        exchange.setProperty("childExceptionFlg", "true");
                     }
                 });
           
}

As per my requirement, when CustomExpection is thrown in the child router, it should add a property to the exchange object and the final handling code needs to be executed in the ExceptionProcessor in the parent router.

1 Answers

What you try to achieve can be done using routes dedicated to error handling that call each other (child error handler route calls parent error handler route) or at least a route for the main error handler that is called by the exception policy of your child routes.

Something like:

// The main logic of the main exception policy is moved to a dedicated
// route called direct:main-error-handler
onException(CustomException.class)
    .to("direct:main-error-handler")
    .handled(true);
from("direct:parent-route").to("direct:child-route");
from("direct:child-route")
    .onException(CustomException.class)
        // Set the exchange property childExceptionFlg to true
        .setProperty("childExceptionFlg", constant("true"))
        // Call explicitly the main logic of the the main exception policy once
        // the property is set
        .to("direct:main-error-handler")
        // Flag the exception as handled
        .handled(true)
    .end()
    // Throw a custom exception to simulate your use case
    .throwException(new CustomException());

from("direct:main-error-handler")
    .log("Property childExceptionFlg set to ${exchangeProperty.childExceptionFlg}");

Result:

INFO  route3 - Property childExceptionFlg set to true
Related