Camel REST服务返回null时引发异常

2020年11月1日 37点热度 0条评论

我有一个简单的REST服务。有客户,我可以通过其ID获得客户。如果没有客户端使用请求的ID,则应返回未找到的404。

这是相关的部分:

rest("/client")
    .consumes("application/json").produces("application/json")
    .get("{id}")
        .to("direct:getClient");

from("direct:getClient")
    .bean(clientService, "getClient(${header.id})")
     .choice()
        .when(simple("${body} == null"))
            .setHeader(Exchange.HTTP_RESPONSE_CODE, constant(404));

当可以找到客户端时,一切都很好,但是,当找不到客户端并且clientService返回null时,我得到以下堆栈跟踪:

org.apache.camel.RuntimeCamelException: java.io.IOException: Stream closed
    at org.apache.camel.http.common.HttpMessage.createBody(HttpMessage.java:74)
    at org.apache.camel.impl.MessageSupport.getBody(MessageSupport.java:47)
    at org.apache.camel.processor.CamelInternalProcessor$StreamCachingAdvice.after(CamelInternalProcessor.java:799)
    at org.apache.camel.processor.CamelInternalProcessor$StreamCachingAdvice.after(CamelInternalProcessor.java:767)
    at org.apache.camel.processor.CamelInternalProcessor$InternalCallback.done(CamelInternalProcessor.java:246)
    at org.apache.camel.processor.RedeliveryErrorHandler.process(RedeliveryErrorHandler.java:573)
    at org.apache.camel.processor.CamelInternalProcessor.process(CamelInternalProcessor.java:197)
    at org.apache.camel.processor.Pipeline.process(Pipeline.java:120)
    at org.apache.camel.processor.Pipeline.process(Pipeline.java:83)
    at org.apache.camel.processor.CamelInternalProcessor.process(CamelInternalProcessor.java:197)
    at org.apache.camel.component.direct.DirectProducer.process(DirectProducer.java:62)
    at org.apache.camel.processor.SendProcessor.process(SendProcessor.java:145)
    at org.apache.camel.management.InstrumentationProcessor.process(InstrumentationProcessor.java:77)
    at org.apache.camel.processor.RedeliveryErrorHandler.process(RedeliveryErrorHandler.java:542)
    at org.apache.camel.processor.CamelInternalProcessor.process(CamelInternalProcessor.java:197)
    at org.apache.camel.processor.Pipeline.process(Pipeline.java:120)

我不知道这一点。从bean方法调用返回null应该是吧?

解决方案如下:

尝试作为解决方法来使用

.setBody().method(clientService, "getClient(${header.id})")

我怀疑它的.bean()在您将
null值作为新消息正文返回时有一个小错误,这使基础
HttpMessage误以为该消息正文尚未初始化,因此您得到该流错误读取再次流。