简体   繁体   中英

How to catch exceptions thrown from reactor?

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM