java 在 Apache Camel 中这种对 null 体的处理能更优雅吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10756004/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 02:25:06  来源:igfitidea点击:

Can this handling of a null body in Apache Camel be more elegant?

javaapache-camelcode-cleanup

提问by Spina

I'm new to Camel and trying to learn idioms and best practices. I am writing web services which need to handle several different error cases. Here is my error handling and routing:

我是 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);

As you can see, I have special handling (content based routing) to deal with a request with a null body. Is there a way to handle this more elegantly? I'm writing several services of this type and it seems like they could be much cleaner.

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

回答by Henryk Konsek

Using body().isNull()expression in content-based routing to redirect nullmessage to Dead Letter Channelis even more than elegant :) . Please note that message redirected to the DLC will still contain headers so you can easily analyze the reason of delivery failure later on.

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

choice().
   when(body().isNull()).to("jms:deadLetterChannel").
   otherwise().to("jms:regularProcessing").
endChoice();

回答by Claus Ibsen

You can use an interceptor, such as interceptFrom with a when, to check for the empty bod, as there is an example of here: http://camel.apache.org/intercept

您可以使用拦截器,例如interceptFrom with a when,来检查空的bod,因为这里有一个例子:http: //camel.apache.org/intercept

And then use stop to indicate no further processing:

然后使用 stop 表示不再进一步处理:

interceptFrom("servlet*").when(body().isNull()).to("direct:syntaxError").stop();

回答by Christian Schneider

You could use a bean that checks for null and throws an exception in case of null. So you could handle this case in your exception handling.

您可以使用检查 null 并在为 null 的情况下抛出异常的 bean。所以你可以在你的异常处理中处理这种情况。