首页 > 解决方案 > apache camel 中 doFinally 块的错误处理

问题描述

我有一个骆驼休息 api,它有一个 doTry、doCatch 和 doFinally 块。我还必须处理 doFinally 块中的错误情况。当使用 doTry .. doCatch .. doFinally 时,常规的 Camel 错误处理程序不适用,因此如何处理 doFinally 块中的错误情况。我to在 doFinally 块中有一个需要错误处理的语句,并且在 doFinally 块的处理器中有一个 if 条件需要错误处理。代码是这样的->

.post("send-req")
  .route()
  .doTry()
    // Some Code
  .doCatch()
   //Some Code 
  .doFinally()
     // Need  error handling for the to statement below
    .to()
    .process(new Processor(){
       @Override
       public void process(Exchange exchange){
           //Need  error handling for the if statement 
          if(condition)
             throw new BadRequestException();
      }
    })
  .endRest();

我尝试像这样进行特定于路由的错误处理->

.post("send-req")
  .route()
  .doTry()
    // Some Code
  .doCatch()
   //Some Code 
  .doFinally()
     // Need  error handling for the to statement below
    .to()
      .onException(SalesforceException.class)
         .handled(true)
         .setHeader(Exchange.HTTP_RESPONSE_CODE, new ValueBuilder(new SimpleExpression("${exception.statusCode}")))
         .transform(exceptionMessage())
         .end()
    .process(new Processor(){
       @Override
       public void process(Exchange exchange){
          //Need  error handling for the if statement 
          if(condition)
             throw new BadRequestException();
       }
    })
    .onException(BadRequestException.class)
       .handled(true)
       .setHeader(Exchange.HTTP_RESPONSE_CODE, constant(400))
       .transform(exceptionMessage())
       .end()                                       
  .endRest();

但这给出了一个错误The output must be added as top-level on the route. Try moving OnException[[org.apache.camel.component.salesforce.api.SalesforceException] -> []] to the top of route。像这样的案件应该如何处理?

标签: error-handlingapache-camel

解决方案


将 onException 块移到路由之外。

它应该是这样的:

onException(SalesforceException.class)
     .handled(true)
     .setHeader(Exchange.HTTP_RESPONSE_CODE, new ValueBuilder(new SimpleExpression("${exception.statusCode}")))
     .transform(exceptionMessage());

onException(BadRequestException.class)
   .handled(true)
   .setHeader(Exchange.HTTP_RESPONSE_CODE, constant(400))
   .transform(exceptionMessage());

rest("/")
.post("send-req")
  .route()
  .someCodeThatThrowsSalesForceException
  .someCodeThatThrowsBadRequestException                         
  .endRest();

推荐阅读