父路由器中的异常处理

Exception handling in parent router

我有一个调用其他路由器的父路由器。父路由器具有所有的异常处理逻辑。在所有子路由器中,在异常情况下,我只想在交换对象中添加属性,并将实际的异常处理留在 parent(main) 路由器中。

示例:

public class ParentRouter extends RouteBuilder {
    @Override 
    public void configure() throws Exception {
        onException(CustomException.class)
            .process(new ExceptionProcessor())
            .handled(true);
         from("direct:parent-route").to("direct:child-route");

         from("direct:child-route")
             .onException(CustomException.class)
                 .process(new Processor(){
                     @Override 
                     public process(Exchange exchange){
                        exchange.setProperty("childExceptionFlg", "true");
                     }
                 });
           
}

按照我的要求,当子路由器中抛出CustomExpection时,它应该在exchange对象中添加一个属性,最后的处理代码需要在[=13中执行=] 在父路由器中。

您尝试实现的目标可以使用专用于相互调用的错误处理的路由(子错误处理程序路由调用父错误处理程序路由)或至少由异常调用的主错误处理程序的路由来完成您的子路线的政策。

类似于:

// The main logic of the main exception policy is moved to a dedicated
// route called direct:main-error-handler
onException(CustomException.class)
    .to("direct:main-error-handler")
    .handled(true);
from("direct:parent-route").to("direct:child-route");
from("direct:child-route")
    .onException(CustomException.class)
        // Set the exchange property childExceptionFlg to true
        .setProperty("childExceptionFlg", constant("true"))
        // Call explicitly the main logic of the the main exception policy once
        // the property is set
        .to("direct:main-error-handler")
        // Flag the exception as handled
        .handled(true)
    .end()
    // Throw a custom exception to simulate your use case
    .throwException(new CustomException());

from("direct:main-error-handler")
    .log("Property childExceptionFlg set to ${exchangeProperty.childExceptionFlg}");

结果:

INFO  route3 - Property childExceptionFlg set to true