Apache Camel可选null以获取头参数

webghufk  于 12个月前  发布在  Apache
关注(0)|答案(1)|浏览(155)

早上好.
目前,我正在开发一个API在Apache Camel中,我必须使用queryParameters的查询和一些参数可能是强制性的,其他人不是,所以我需要处理的情况下,我不发送参数有一些方法来处理nullPointerException,我使用的是可选的,但是,我不知道我是否使用它不正确,但我没有得到错误:
目前我使用下面的代码行,理论上如果它收到一个空值,它将返回一个空的可选值,但是,我得到一个错误:

Optional<String> optionalServices= Optional.ofNullable(exchange.getIn().getHeader("services").toString());

字符集
例外

Stacktrace
---------------------------------------------------------------------------------------------------------------------------------------: java.lang.NullPointerException: Cannot invoke "Object.toString()" because the return value of "org.apache.camel.Message.getHeader(String)" is null
    at org.tmve.customer.ms.processor.UserProfileProcessorQueryParamReq.process(UserProfileProcessorQueryParamReq.java:35)
    at org.apache.camel.support.processor.DelegateSyncProcessor.process(DelegateSyncProcessor.java:65)
    at org.apache.camel.impl.engine.CamelInternalProcessor.process(CamelInternalProcessor.java:392)
    at org.apache.camel.processor.Pipeline$PipelineTask.run(Pipeline.java:104)
    at org.apache.camel.impl.engine.DefaultReactiveExecutor$Worker.schedule(DefaultReactiveExecutor.java:181)
    at org.apache.camel.impl.engine.DefaultReactiveExecutor.scheduleMain(DefaultReactiveExecutor.java:59)
    at org.apache.camel.processor.Pipeline.process(Pipeline.java:165)
    at org.apache.camel.impl.engine.CamelInternalProcessor.process(CamelInternalProcessor.java:392)
    at org.apache.camel.component.platform.http.vertx.VertxPlatformHttpConsumer.lambda$handleRequest$2(VertxPlatformHttpConsumer.java:201)
    at io.vertx.core.impl.ContextBase.lambda$null$0(ContextBase.java:137)
    at io.vertx.core.impl.ContextInternal.dispatch(ContextInternal.java:264)
    at io.vertx.core.impl.ContextBase.lambda$executeBlocking$1(ContextBase.java:135)
    at org.jboss.threads.ContextHandler$1.runWith(ContextHandler.java:18)
    at org.jboss.threads.EnhancedQueueExecutor$Task.run(EnhancedQueueExecutor.java:2449)
    at org.jboss.threads.EnhancedQueueExecutor$ThreadBody.run(EnhancedQueueExecutor.java:1478)
    at org.jboss.threads.DelegatingRunnable.run(DelegatingRunnable.java:29)
    at org.jboss.threads.ThreadLocalResettingRunnable.run(ThreadLocalResettingRunnable.java:29)
    at io.netty.util.concurrent.FastThreadLocalRunnable.run(FastThreadLocalRunnable.java:30)
    at java.base/java.lang.Thread.run(Thread.java:840)


这是我如何测试从postman时,它不发送值:


的数据
在这种情况下,如果查询参数的值没有被发送,我该如何处理它?

bvuwiixz

bvuwiixz1#

根据错误日志,Message.getHeader(String)返回null。
你的陈述可以更正如下。

Optional<String> optionalServices= Optional.ofNullable(exchange.getIn().getHeader("services"))
                .map(Object::toString)

字符集
如果我用多个步骤来解释上面的话。

Optional<Object> optObj = Optional.ofNullable(exchange.getIn().getHeader("services")); 
Optional<String> optStr = optObj.map(obj -> obj.toString());


因此,Optional.map()中的函数(obj -> obj.toString())只有在Optional有值时才被调用。

相关问题