How to handle errors in Spring reactor Mono or Flux?

后端 未结 5 2172
难免孤独
难免孤独 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:16

    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();
    

提交回复
热议问题