如何从反应堆中捕获例外?

发布于 2025-01-28 23:34:11 字数 1236 浏览 2 评论 0原文

我想从通量中捕获异常,我的代码是这样的:

        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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

暖伴 2025-02-04 23:34:11

您可以使用onerror()操作员处理错误案例,或者如果您想记录异常,则可以使用doonError()操作员。

You can use the onError() operator to handle error cases, or the doOnError() operator if you e.g. want to log the exception.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文