Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle errors in Spring reactor Mono or Flux?

I have below code retuning Mono<Foo>:

try {
    return userRepository.findById(id)  // step 1
        .flatMap(user -> barRepository.findByUserId( user.getId())  // step 2
        .map(bar-> Foo.builder().msg("Already exists").build())  // step 3
            .switchIfEmpty(barRepository.save(Bar.builder().userId(user.getId()).build())  // step 4
                .map(bar-> Foo.builder().msg("Created").build())   // step 5 
            ))
            .doOnError(throwable -> Mono.just(handleError(throwable)));
    } catch(Exception e) {

        log.error("from catch block");
        return Mono.just(handleError(e));

    }

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?

Same question if error happens in step 2, step3, step 4.

What is the correct code so that error is always caught by doOnError and eliminate try catch?

I am using public interface UserRepository extends ReactiveMongoRepository<User, String> same for barRepository.

handleError(throwable) simply does log.error(e.getMessage() and retuns Foo.

like image 644
ace Avatar asked Jun 25 '18 13:06

ace


People also ask

How do you handle errors in mono zip?

Use the zip operator and handle the error case with a fallback operator like onErrorResume or retry on the zipped Mono or any upstream one.

How do you handle empty mono?

Default value if mono is empty. If you want to provide a default value when the mono is completed without any data, then use defaultIfEmpty method. For example, the following code tries to fetch the customer data from the database by using the customer id .

What is mono and flux in reactive programming Spring?

Mono — A publisher that can emit 0 or 1 element. Flux — A publisher that can emit 0.. N elements.

What is the difference between mono and flux?

A Flux object represents a reactive sequence of 0.. N items, while a Mono object represents a single-value-or-empty (0..1) result. This distinction carries a bit of semantic information into the type, indicating the rough cardinality of the asynchronous processing.


1 Answers

I think the first error is in the title: "Mono or Flux" is not related with the error handling.

  • Mono can only emit one item at the most (streams one element)
  • Flux can emit more complex stuff (i.e. List)

To handle errors you can follow this example:

return webClient.get()
                .uri(url)
                .retrieve()
                .bodyToMono(ModelYouAreRetrieving.class)
                .doOnError(throwable -> logger.error("Failed for some reason", throwable))
                .onErrorReturn(new ModelYouAreRetrieving(...))
                .block();
like image 192
Andrea Ciccotta Avatar answered Dec 30 '22 20:12

Andrea Ciccotta