【问题标题】:Spring Reactor: How to throw an exception when publisher emit a value?Spring Reactor:发布者发出值时如何抛出异常?
【发布时间】:2019-08-25 09:15:06
【问题描述】:

我正在学习使用 Reactor 进行反应式编程,并且我想实现注册场景,其中用户可以将多个帐户分配给同一个配置文件。但是,分配给个人资料的用户名和分配给帐户的电话必须是唯一的。

正如您在下面的 sn-p 中看到的,如果 Reactor 提供运算符 switchIfNotEmpty,则此场景将很容易实现。

public Mono<PersonalAccountResponse> createPersonalAccount(PersonalAccountRequest request) {
    return Mono
            .just(request.isAlreadyUser())
            .flatMap(isAlreadyUser ->  {
                if(isAlreadyUser){
                    return profileDao
                            .findByUsername(request.getUsername()) //
                            .switchIfEmpty(Mono.error(() -> new IllegalArgumentException("...")));
                }else{
                    return profileDao
                            .findByUsername(request.getUsername())
                            .switchIfEmpty(Mono.from(profileDao.save(profileData)))
                            .switchIfNotEmpty(Mono.error(() -> new IllegalArgumentException("...")));
                }
            })
            .map(profileData -> personalAccountMapper.toData(request))
            .flatMap(accountData -> personalAccountDao
                                            .retrieveByMobile(request.getMobileNumber())
                                            .switchIfEmpty(Mono.from(personalAccountDao.save(accountData)))
                                            .switchIfNotEmpty(Mono.error(() -> new IllegalArgumentException("..."))))
            .map(data ->  personalAccountMapper.toResponse(data, request.getUsername()));
}

如果没有switchIfNotEmpty,我该如何实现这个要求?

谢谢

【问题讨论】:

    标签: if-statement exception switch-statement project-reactor


    【解决方案1】:

    要在发布者发出值时传播异常,您可以使用对发出的值进行操作的多个运算符之一。

    一些例子:

    fluxOrMono.flatMap(next -> Mono.error(new IllegalArgumentException()))
    
    fluxOrMono.map(next -> { throw new IllegalArgumentException(); })
    
    fluxOrMono.doOnNext(next -> { throw new IllegalArgumentException(); })
    
    fluxOrMono.handle((next, sink) -> sink.error(new IllegalArgumentException()))
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多