title: How to handle errors in Spring reactor Mono or Flux?
body: <p>I have below code retuning Mono&lt;Foo&gt;:</p>
  
  <pre><code>try {
      return userRepository.findById(id)  // step 1
          .flatMap(user -&gt; barRepository.findByUserId( user.getId())  // step 2
          .map(bar-&gt; Foo.builder().msg("Already exists").build())  // step 3
              .switchIfEmpty(barRepository.save(Bar.builder().userId(user.getId()).build())  // step 4
                  .map(bar-&gt; Foo.builder().msg("Created").build())   // step 5 
              ))
              .doOnError(throwable -&gt; Mono.just(handleError(throwable)));
      } catch(Exception e) {
  
          log.error("from catch block");
          return Mono.just(handleError(e));
  
      }
  </code></pre>
  
  <p>If error occurs in step 1 (e.g. user does not exist by the specified id), will it be caught by doOnError or by try catch block or none of these two?</p>
  
  <p>Same question if error happens in step 2, step3, step 4. </p>
  
  <p>What is the correct code so that error is always caught by doOnError and eliminate try catch?</p>
  
  <p>I am using 
  <code>public interface UserRepository extends ReactiveMongoRepository&lt;User, String&gt;</code> same for barRepository.</p>
  
  <p>handleError(throwable) simply does log.error(e.getMessage() and retuns Foo.</p>