如何从反应堆中捕获例外?
我想从通量中捕获异常,我的代码是这样的:
try {
Flux.just("key1", "key2", "key3")
.doOnNext(System.out::println)
.map(k -> {
if (!k.equals("key1")) {
throw new RuntimeException("Not key1"); // 1
}
return "External Value, key:" + k;
})
.subscribe(System.out::println); // 2
} catch (Throwable e) {
System.out.println("Got exception"); // 3
}
输出是:
key1
External Value, key:key1
key2
[ERROR] (main) Operator called default onErrorDropped - reactor.core.Exceptions$ErrorCallbackNotImplemented: java.lang.RuntimeException: Not key1
reactor.core.Exceptions$ErrorCallbackNotImplemented: java.lang.RuntimeException: Not key1
Caused by: java.lang.RuntimeException: Not key1
at com.cxd.study.reactor.HandlingErrors.lambda$catchException$7(HandlingErrors.java:153)
...
看来我的 catch 在步骤3中从未达到。
我知道我可以在这样的步骤2上找到例外:.subscribe(System.out :: println,e-> system.out.println(“ get exception'exception'))
。
但是,我该如何从步骤1中抓住例外呢?
I want to catch exceptions thrown from a flux, my code is like this:
try {
Flux.just("key1", "key2", "key3")
.doOnNext(System.out::println)
.map(k -> {
if (!k.equals("key1")) {
throw new RuntimeException("Not key1"); // 1
}
return "External Value, key:" + k;
})
.subscribe(System.out::println); // 2
} catch (Throwable e) {
System.out.println("Got exception"); // 3
}
the output is:
key1
External Value, key:key1
key2
[ERROR] (main) Operator called default onErrorDropped - reactor.core.Exceptions$ErrorCallbackNotImplemented: java.lang.RuntimeException: Not key1
reactor.core.Exceptions$ErrorCallbackNotImplemented: java.lang.RuntimeException: Not key1
Caused by: java.lang.RuntimeException: Not key1
at com.cxd.study.reactor.HandlingErrors.lambda$catchException$7(HandlingErrors.java:153)
...
It seems that my catch at step 3 is never reached.
I know I can reach the exception at step 2 like this:.subscribe(System.out::println, e -> System.out.println("Got Exception"))
.
But how can I catch the exception thrown at step 1 out of the flux?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以使用
onerror()
操作员处理错误案例,或者如果您想记录异常,则可以使用doonError()
操作员。You can use the
onError()
operator to handle error cases, or thedoOnError()
operator if you e.g. want to log the exception.