java - Mono.subscribe() 向客户端抛出异常
问题描述
我试图找出为什么运行时异常没有传播回客户端。我有下一段代码,所以当我返回 Mono.error 时,应该在订阅错误部分进行处理,以便向客户端抛出异常,但这并没有发生。知道我做错了吗?
public void onmethod(EventDetails eventDetails, String eventType) {
messageConverter.convertAndSendMessage(eventType, eventDetails)
.flatMap(aBoolean -> {
if (aBoolean)
log.debug("Event published");
else {
log.debug("Problem publishing event.");
return Mono.error(new RuntimeException("Problem publishing event."));
}
return Mono.just(true);
})
.doOnError(throwable -> log.error("Failed to consume message", throwable))
.subscribe(
next -> { } ,
error -> {
throw Exceptions.propagate(error);
}
);
}
这是我必须验证方法行为的测试。由于抛出任何异常,此测试失败。但是,我可以在日志中看到发生了异常。
Assertions.assertThrows(RuntimeException.class, () ->
consentsListener.onmethod(
eventDetails, "eventType")
);
19:44:32.463 [main] ERROR events.auth.ConsentsListenerImpl - Failed to consume message
java.lang.RuntimeException: Problem publishing event.
at events.auth.ConsentsListenerImpl.lambda$publishMessage$0(ConsentsListenerImpl.java:121)
at reactor.core.publisher.FluxFlatMap.trySubscribeScalarMap(FluxFlatMap.java:152)
at reactor.core.publisher.MonoFlatMap.subscribeOrReturn(MonoFlatMap.java:53)
at reactor.core.publisher.Mono.subscribe(Mono.java:4084)
at reactor.core.publisher.Mono.subscribeWith(Mono.java:4214)
at reactor.core.publisher.Mono.subscribe(Mono.java:4070)
at reactor.core.publisher.Mono.subscribe(Mono.java:4006)
at reactor.core.publisher.Mono.subscribe(Mono.java:3978)
at ...
org.opentest4j.AssertionFailedError: Expected java.lang.RuntimeException to be thrown, but nothing was thrown.
非常感谢您提前。此致。
解决方案
我试图找出为什么运行时异常没有传播回客户端。
因为您正在订阅它,这几乎可以肯定是错误的做法。框架(在这种情况下为 Webflux)应该是控制对您的发布者的订阅。
如果您删除subscribe()
该链上的调用,将您的方法更改为返回Mono<Boolean>
,然后在该方法中返回整个链,它应该按预期工作。
推荐阅读
- docker - 如何允许 docker 容器通过 localhost 与另一个容器通信
- discord - 如何嵌入机器人的回复?不和谐.js
- javascript - Javascript:复制不同 MIME 类型的独立对象
- javascript - 是否可以在打字稿中减少具有未知属性名称的通用对象?
- python-3.x - 如何向 Plotly 图形添加辅助标题
- r - 通过更改值来更改数据框的列名 - R
- c++ - 使用向量和字符串时双倍释放
- function - Roblox 中未装备触发器的失败
- c# - 使用 Postman 而不是 Bot Framework Emulator 测试我的机器人
- javascript - 如何在 Netbeans 上获得对最新 javascript 的支持?