Search code examples
javaexceptionapache-cameldslspring-camel

Camel doesn't catch Exception


.from("seda:rest_upload")
                .process(new Processor() {
                    @Override
                    public void process(Exchange exchange) {
                        if(true){
                            throw new RuntimeException();
                        }})
                .to("seda:parsed_csv")
                .onException(Exception.class).process(new Processor() {
            @Override
            public void process(Exchange exchange) throws Exception {
                logger.warn("Error");
            }
        });

But logger.warn("Error"); was not invoked.

What do I wrong?

How can I register global exception handler for camel route?


Solution

  • Move onException block on top of the route and do not forget on end() terminator.

    end() tells Camel, where the onException block ends. If you ommit that, Camel treats it as one onException block. Simply there will be route consuming from seda and no output processor, because everything after onException() gets part of onException block.


    Route-specific exception handling: Handle exceptions occured in route seda:rest_upload

    from("seda:rest_upload")
        .onException(Exception.class).process(exchange -> logger.warn("Error")).end()
        .process(e -> {throw new RuntimeException();})
        .to("seda:parsed_csv");
    
    from("seda:parsed_csv").to("log:parsed_csv");
    
    from("timer:tmr?period=1000")
        .setBody(constant("mock"))
        .to("seda:rest_upload");
    

    Global exception handling: Handle exceptions in all routes in current RouteBuilder

    onException(Exception.class).process(exchange -> logger.warn("Error")); //There is no need for end(), whole block is part of onException block
    
    from("seda:rest_upload")
        .process(e -> {throw new RuntimeException();})
        .to("seda:parsed_csv");
    
    from("seda:parsed_csv").to("log:parsed_csv");
    
    from("timer:tmr?period=1000")
        .setBody(constant("mock"))
        .to("seda:rest_upload");