![](/img/trans.png)
[英]Spring Webflux Reactive Mongo Bulk Operations (Java)
[英]Webflux data check with mongo reactive spring
我嘗試學習Webflux,但是當我想在保存數據之前驗證員工的列表ID時遇到了問題。 我的問題如何解決,當不存在受雇身份並向客戶端顯示錯誤時如何捕獲錯誤?
@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 Config中添加自定義異常處理程序。
您可以在此處閱讀更多詳細信息: Web-active
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.