Camel Exception handling doesnt work if exception clause is defined in a separate class

大憨熊 提交于 2019-11-30 20:12:27

correct, the onException() clauses only apply to the current RouteBuilder's route definitions...

that said, you can reuse these definitions by having all your RouteBuilders extend the ExceptionRouteBuilder and call super.configure()...something like this

public class MyRouteBuilder extends ExceptionRouteBuilder {
    @Override
    public void configure() throws Exception {
        super.configure();
        from("direct:start").throwException(new Exception("error"));
    }
}
...
public class ExceptionRouteBuilder implements RouteBuilder {
    @Override
    public void configure() throws Exception {
        onException(Exception.class).handled(true).to("mock:error");
    }
}

or even just have a static method in an ExceptionBuilder class to setup the clauses for a given RouteBuilder instance

public class MyRouteBuilder extends RouteBuilder {
    @Override
    public void configure() throws Exception {
        ExceptionBuilder.setup(this);
        from("direct:start").throwException(new Exception("error"));
    }
}
...
public class ExceptionBuilder {
    public static void setup(RouteBuilder routeBuilder) {
        routeBuilder.onException(Exception.class).handled(true).to("mock:error");
    }  
}

Based on the accepted answer, I found a cleaner way to implement exception handling, so you don't have to call super.configure() in every route. Just call a method that handles onException in the constructor of the base class.

//Base class that does exception handling
public abstracExceptionRouteBuildert class BaseAbstractRoute extends RouteBuilder {
  protected BaseAbstractRoute() {
    handleException();
  }

  private void handleException() {
    onException(Exception.class).handled(true).to("mock:error");
  }
}

//Extend the base class
public class MyRouteBuilder extends BaseAbstractRoute {
  @Override
  public void configure() throws Exception {
    from("direct:start").throwException(new Exception("error"));
  }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!