问题描述
我正在使用Reactor学习反应式编程,我想实现注册方案,在该方案中,用户可以将多个帐户分配给同一个人资料。但是,分配给配置文件的用户名和分配给帐户的电话必须唯一。
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.
如下面的代码片段所示,如果满足以下条件,这种情况将很容易实现Reactor正在向操作员提供 switchIfNotEmpty
。
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()));
}
如何在没有 switchIfNotEmpty的情况下实现此要求
?
谢谢
推荐答案
发布者发出值时出现例外,可以使用对发出的值进行操作的多个运算符之一。
To propagate an exception when a publisher emits a value, you can use one of several operators that operate on emitted values.
一些示例:
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()))
这篇关于Spring Reactor:发布者发出值时如何引发异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!