springspring-bootapache-camelspring-camelcamel-ftp

Global exception handler across the camel context – covering all routes


I have camel 10 camel routes something like below:

@AllArgsConstructor
public class MyCamelRoute extends RouteBuilder {

    /**
     * {@inheritDoc}
     */
    @Override
    public void configure() throws Exception {
    }
}  

Above MyCamelRoute is created using below code which loads Camel route into Spring container:

 @Bean("myCamelRoute")
 public RouteBuilder createMyCamelRoute () {
        return new MyCamelRoute();
 }

Now I need to have a global exception handler across the Camel context – covering all routes.


Solution

  • You can define a global exception clause for all routes defined inside a Routebuilder, from the camel documentation

    Global scope for Java DSL is per RouteBuilder instance, so if you want to share among multiple RouteBuilder classes, then create a base abstract RouteBuilder class and put the error handling logic in its configure method. And then extend this class, and make sure to class super.configure(). We are just using the Java inheritance technique.

    In other words, the BaseRouteBuilder class would be:

    public abstract BaseRouteBuilder extends RouteBuilder {
    
    @Override
    public void configure() {
       onException(Throwable.class).log("Excpetion caught");
    }
    

    And then your routes:

    @AllArgsConstructor
    public class MyCamelRoute extends BaseRouteBuilder {
    
        /**
         * {@inheritDoc}
         */
        @Override
        public void configure() throws Exception {
            super.configure();
            // Route Configuration here
        }
    

    }

    As pointed out, it is important to call super.configure() from the child class, otherwise the exception clause will not be executed.