How to handle errors in Spring reactor Mono or Flux?

后端 未结 5 2148
难免孤独
难免孤独 2021-01-05 17:02

I have below code retuning Mono:

try {
    return userRepository.findById(id)  // step 1
        .flatMap(user -> barRepository.findByUserId( u         


        
5条回答
  •  春和景丽
    2021-01-05 17:24

    @Gianluca Pinto's last line of code is also incorrect. The code won't be compiled. onErrorReturn is not suitable for complicated error handling. What you should use is onErrorResume.

    see: https://grokonez.com/reactive-programming/reactor/reactor-handle-error#21_By_falling_back_to_another_Flux

    onErrorResume will fall back to another Flux and let you catch and manage the exception thrown by previous Flux. if look into the implementation of onErrorReturn, you will find onErrorReturn is actually using onErrorResume.

    So here the code should be:

    .onErrorResume(throwable -> Mono.just(handleError(throwable)));
    

提交回复
热议问题