Apache Camel中对null体的处理能否更优雅?

Spi*_*ina 3 java code-cleanup apache-camel

我是Camel的新手,并试图学习习语和最佳实践.我正在编写需要处理几种不同错误情况的Web服务.这是我的错误处理和路由:

onException(JsonParseException.class).inOut("direct:syntaxError").handled(true);
onException(UnrecognizedPropertyException.class).inOut("direct:syntaxError").handled(true);

// Route service through direct to allow testing.
from("servlet:///service?matchOnUriPrefix=true").inOut("direct:service");
from("direct:service")
    .choice()
        .when(body().isEqualTo(null))
            .inOut("direct:syntaxError")
        .otherwise()
            .unmarshal().json(lJsonLib, AuthorizationParameters.class).inOut("bean:mybean?method=serviceMethod").marshal().json(lJsonLib);
Run Code Online (Sandbox Code Playgroud)

如您所见,我有特殊处理(基于内容的路由)来处理具有空主体的请求.有没有办法更优雅地处理这个问题?我正在写几种这种类型的服务,看起来它们可以更清洁.

Cla*_*sen 6

您可以使用拦截器(例如interceptFrom和when)来检查空身体,因为这里有一个示例:http://camel.apache.org/intercept

然后使用stop表示没有进一步处理:

interceptFrom("servlet*").when(body().isNull()).to("direct:syntaxError").stop();
Run Code Online (Sandbox Code Playgroud)


Hen*_*sek 6

body().isNull()在基于内容的路由中使用表达式将null消息重定向到死信频道甚至不仅仅是优雅:).请注意,重定向到DLC的邮件仍会包含标题,因此您可以在以后轻松分析传递失败的原因.

choice().
   when(body().isNull()).to("jms:deadLetterChannel").
   otherwise().to("jms:regularProcessing").
endChoice();
Run Code Online (Sandbox Code Playgroud)