Apache Camel onException

被刻印的时光 ゝ 提交于 2020-01-13 09:49:52

问题


I want to catch all Exception from routes.

I add this OnExeption :

onException(Exception.class).process(new MyFunctionFailureHandler()).stop();

Then, I create the class MyFunctionFailureHandler.

public class MyFunctionFailureHandler  implements Processor {

@Override
public void process(Exchange exchange) throws Exception {
    Throwable caused;

    caused = exchange.getProperty(Exchange.EXCEPTION_CAUGHT, Throwable.class);

    exchange.getContext().createProducerTemplate().send("mock:myerror", exchange);
   }

}

Unfortunately, it doesn't work and I don't know why.

if there is an Exception, the program must stop.

How can I know why this code doesn't work!!

Thanks.


回答1:


I used this on my route:

public class MyCamelRoute extends RouteBuilder {

   @Override
   public void configure() throws Exception {

        from("jms:start")
           .process(testExcpProcessor)

       // -- Handle Exceptions
       .onException(Exception.class)
         .process(errorProcessor)
         .handled(true)

       .to("jms:start");
   }
}

and in my errorProcessor

public class ErrorProcessor implements Processor {

  @Override
  public void process(Exchange exchange) throws Exception {


    Exception cause = exchange.getProperty(Exchange.EXCEPTION_CAUGHT, Exception.class);

    if(cause != null){
        log.error("Error has occurred: ", cause);

        // Sending Error message to client
        exchange.getOut().setBody("Error");
    }else

        // Sending response message to client
        exchange.getOut().setBody("Good");
  }
}

I hope it helps




回答2:


keep in mind that if you have routes in multiple RouteBuilder classes, having an onExcpetion within this route will affect all routes under this RouteBuilder only

review this answer

additionally if an exception occurs within a route and handled inside this route,it won't be propagated to the original caller route you need to use noErrorHandler() i.e. from(direct:start).errorHandler(noErrorHandler()) to propagate the exception handling back to the caller



来源:https://stackoverflow.com/questions/14198043/apache-camel-onexception

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!