'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?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source