0

I have some methods in my reactive chain that can throw exception. If an exception happens - I don't want to continue executing the chain, and I want to log - what exact action threw the exception.

I wrote a code, that looks something like this:

   Mono<Void> mono = Mono.just(10)
            .map(a -> action1(a))
            .doOnError((t) -> System.out.println("action 1 threw an exception"))
            .onErrorStop()
            .map(a -> action2(a)) 
            .doOnError((t) -> System.out.println("action 2 threw an exception"))
            .then();
    
    mono.subscribe();

but when action1 throws an exception - I get the following output:

action 1 threw an exception
action 2 threw an exception

what's not what I expected

akarnokd
  • 69,132
  • 14
  • 157
  • 192
a3dsfcv
  • 1,146
  • 2
  • 20
  • 35
  • Errors are propagated through the reactive chain. If you need these logs only to have a proper stack trace, then check out the debugging section in the reference: https://projectreactor.io/docs/core/release/reference/#debugging – Martin Tarjányi Dec 17 '20 at 21:40

1 Answers1

1
  1. You need to think the reactive chain as a pipeline or a data flow.In the pipeline , the error is also a data as same as others.
  2. The flatMap() method change the signal to another (Mono or Flux) when data is available.
Mono<Void> mono = Mono.just(10)
                .map(a -> action1(a))
                .doOnError((t) -> System.out.println("action 1 threw an exception"))
                .flatMap(a -> Mono.just(a)
                        .map(value -> action2(value))
                        .doOnError((t) -> System.out.println("action 2 threw an exception"))
                        .then()
                )
                .then();
        mono.subscribe();
Cheng Gang
  • 26
  • 2