Search code examples
springapache-camelspring-camel

How to implement OnException and errorHandler in a camel route and spring boot?


I would like to use onExceptionProcessor to catch any exceptions catched by my route builder and save them in the database.

I don't khnow if i have to use onException(Exception.class) or errorHandler() and how to implement them correctly!

I tried the try-catch but it does not catch my exception (null pointer that i throw in the processor1). May be i do not implement it correctly ?

Here is my routeBuilder:

@component
public class MyRoute extends RouteBuilder {

  @Autowired
  private Processor processor1;  

  @Autowired
  private Processor procssor2;  

  @Autowired
  private Processor processor3;

  @Autowired
  private Processor onExceptionProcessor; // it a processor where i try to save the stacktrace of exception in the database

  @Override
  public void configure() throws Exception {
    from(jmsDecoupageRouteIn)
        .id("route_id_processing").messageHistory().transacted()
        .log(LoggingLevel.DEBUG, log, "It's for just for log").pipeline()
        .process(processor1)
        .id(processor1.getClass().getSimpleName().toLowerCase())
        .process(procssor2)
        .id(procssor2.getClass().getSimpleName().toLowerCase())
        .process(processor3)
        .id(processor3.getClass().getSimpleName().toLowerCase())
        .doTry()
        .to(jmsDecoupageRouteOut)
        .doCatch(Exception.class)
        .log(LoggingLevel.ERROR, "EXCEPTION: ${exception.stacktrace}")
        .process(onExceptionProcessor)
        .id(onExceptionProcessor.getClass().getSimpleName().toLowerCase())
        .endDoTry();
  }
}

Solution

  • This is the generic structure of a doTry()...doCatch()...end() construct.

     from("direct:start")
                        .doTry()
                            .process(new ProcessorFail())
                            .to("mock:result")
                        .doCatch(IOException.class, IllegalStateException.class)
                            .to("mock:catch")
                        .doFinally()
                            .to("mock:finally")
                        .end();
    
    

    In your case you are using a .endDoTry() instead of .end(). Its a tiny gotcha in the Camel API. Change it and see if it works as expected.

    Additional Reference

    Keep in mind that when you use doTry()...doCatch()...end() the regular Camel OnException handlers will not work (You can't mix them together).

    Update: Screenshot as shared with OP Exception handling processor definition