Spring Reactor: How to throw an exception when publisher emit a value?

我的未来我决定 提交于 2019-12-25 01:27:28

问题


I'm learning reactive programming with Reactor and I want to implement registration scenario where a user can have many accounts assigned to the same profile. However the username assigned to the profile and the phone assigned to the account must be unique.

As you can see in the following snippet, this scenario will be easy to implement if Reactor was offering the operator 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()));
}

How can I implement this requirement without switchIfNotEmpty?

Thanks


回答1:


To propagate an exception when a publisher emits a value, you can use one of several operators that operate on emitted values.

Some examples:

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


来源:https://stackoverflow.com/questions/55501980/spring-reactor-how-to-throw-an-exception-when-publisher-emit-a-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!