如何处理Spring Reactor Mono或Flux中的错误? [英] How to handle errors in Spring reactor Mono or Flux?

查看:1790
本文介绍了如何处理Spring Reactor Mono或Flux中的错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在下面的代码中重新调整了Mono< Foo>:

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

    }

如果在第1步中发生错误(例如,指定的ID不存在该用户),是否会被doOnError或try catch块捕获,或者这两个都不捕获?

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?

同一问题,是否在步骤2,步骤3,步骤4中发生错误.

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

什么是正确的代码,以便使错误始终被doOnError捕获并消除try catch?

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

我正在使用 public interface UserRepository extends ReactiveMongoRepository<User, String>与barRepository相同.

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

handleError(throwable)仅执行log.error(e.getMessage()并重新调整Foo.

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

推荐答案

DoOnError仅会产生副作用,并且如果findById失败,则它会返回Mono.Error().

DoOnError will only perform side effects and assuming the findById are will return a Mono.Error() if it fails something like this should work.

return userRepository.findById(id)
    .flatMap ( user -> 
        barRepository.findByUserId(user.getId())
        .map((user,bar)-> Foo.builder().msg("Already exists").build())  
        .switchIfEmpty(barRepository.save(Bar.builder().userId(user.getId()).build())
        .map(bar-> Foo.builder().msg("Created").build())

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

仅当您调用链的阻塞操作,或者在进入反应式链之前发生运行时错误时,try catch才起作用. doOn操作不会修改链,它们仅用于副作用.由于flatMap需要生产者,因此您需要从调用中返回Mono,在这种情况下,如果发生错误,则它将传播错误.除非另行处理,否则所有反应链中的错误都会传播.

The try catch will only work if you either call a blocking operation of the chain, or a runtime error occurs before you enter the reactive chain. the doOn operations do not modify the chain, they are used for side effects only. Since flatMap expects a producer, you will need to return a Mono from the call, and in this case if an error occurs, then it will just propagate the error. In all reactive chains the error will propagate unless otherwise handled.

这篇关于如何处理Spring Reactor Mono或Flux中的错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆