Java 使用mongo反应弹簧检查Webflux数据
我试图学习Webflux,但当我想在保存数据之前验证员工的列表id时,我遇到了一个问题。 还有我的问题 当employeId不存在时,如何捕获错误并将错误显示给客户端Java 使用mongo反应弹簧检查Webflux数据,java,spring,spring-boot,spring-webflux,Java,Spring,Spring Boot,Spring Webflux,我试图学习Webflux,但当我想在保存数据之前验证员工的列表id时,我遇到了一个问题。 还有我的问题 当employeId不存在时,如何捕获错误并将错误显示给客户端 @PostMapping(path = "/{tenantId}/outlet") public Mono<OutletEntity> createNewOutlet(@PathVariable String tenantId, @RequestBody OutletEntity outletEntity) {
@PostMapping(path = "/{tenantId}/outlet")
public Mono<OutletEntity> createNewOutlet(@PathVariable String tenantId, @RequestBody OutletEntity outletEntity) {
return Mono.just(outletEntity).map(outletEntity1 -> {
outletEntity.getEmployees().forEach(s -> {
this.employeeService.getRepository().existsById(s).subscribe(aBoolean -> {
System.out.println(aBoolean);
if (!aBoolean) {
/**
* variable s is employeId
* i want to validate every single employee id before save new outlet
*/
throw new ApiExceptionUtils("tenant not found", HttpStatus.UNPROCESSABLE_ENTITY.value(),
StatusCodeUtils.TENANT_NOT_FOUND);
}
});
});
return outletEntity1;
}).flatMap(outletEntity1 -> {
outletEntity.setTenantId(tenantId);
return this.outletRepository.save(outletEntity);
});
更好的方法是在同一链中运行验证,而无需额外订阅服务器
return Flux.fromIterable(outletEntity.getEmployees()) (1)
.flatMap(this.employeeService.getRepository()::existsById)
.doOnNext(System.out::println)
.map(aBoolean -> {
if (!aBoolean) { (2)
throw new ApiExceptionUtils("tenant not found", HttpStatus.UNPROCESSABLE_ENTITY.value(),
StatusCodeUtils.TENANT_NOT_FOUND);
}
else {
return aBoolean;
}
})
.then(Mono.just(outletEntity)) (3)
.flatMap(outletEntity1 -> {
outletEntity.setTenantId(tenantId);
return this.outletRepository.save(outletEntity);
});
1从员工收集中创建流量,并通过反应器流进行迭代,并进行验证
2检查您的类型是否为false并抛出异常,它将停止此链
3若一切运行顺利,则切换到带outletEntity的Mono,保存并返回
关于错误处理。
如果不处理错误,WebFlux将在DefaultErrorWebExceptionHandler中解决它
您可以像在Web MVC中一样添加自己的错误处理程序,也可以在WebFlux配置中添加自定义异常处理程序
您可以在此处阅读更多详细信息:使用此代码时,会调用异常并在终端中打印,但客户端不知道employeeId不存在,请求已成功存储到数据库中。我的目标是当employeId不存在时抛出异常并无法保存和发送错误响应。我明白你的意思,我根据你的问题更正了我的答案。哇,它成功了。我有更多的问题,如果,我们需要更多的验证,结合单声道和通量。在outletEntity中有两个通量必须验证。请随意提问