Spring被动-如何处理调用方法中的mono.error
我是新来的春天数据反应卡桑德拉。在我的服务类中,我正在注入ReactiveCassandraRepository的实现,如果它通过给定的id找到pojo,它将返回pojo的MonoSpring被动-如何处理调用方法中的mono.error,spring,exception-handling,mono,spring-webflux,reactive,Spring,Exception Handling,Mono,Spring Webflux,Reactive,我是新来的春天数据反应卡桑德拉。在我的服务类中,我正在注入ReactiveCassandraRepository的实现,如果它通过给定的id找到pojo,它将返回pojo的Mono public Mono<MyPojo> getResult(String id) { return myRepository.findById(id) .flatMap(result -> result!=null ? getDecision(result) :
public Mono<MyPojo> getResult(String id) {
return myRepository.findById(id)
.flatMap(result -> result!=null ? getDecision(result) :
Mono.error(new Exception("result not found for id: "+id)));
}
private Mono<? extends MyPojo> getDecision(MyPojoDto result) {
if(result.getRecommendation()==0) {
return Mono.just(MyPojo.builder().result("Accept").build());
}
else
{
return Mono.just(MyPojo.builder().result("Reject").build());
}
}
public Mono getResult(字符串id){
返回myRepository.findById(id)
.flatMap(结果->结果!=null?getDecision(结果):
Mono.error(新异常(“未找到id:+id的结果”);
}
private Mono看起来您的存储库在找不到任何记录时返回空的Mono
您可以更改getResult
方法:
return myRepository.findById(id)
.flatMap(result -> getDecision(result))
.switchIfEmpty(Mono.error(new Exception("result not found for id: " + id)));
或者,如果不想创建任何异常的实例,可以更改控制器:
return myService.getResult(id)
.flatMap(result -> getCustomResponse(id, result, HttpStatus.OK))
.switchIfEmpty(getCustomResponse(id, result, HttpStatus.NOT_FOUND));
return myService.getResult(id)
.flatMap(result -> getCustomResponse(id, result, HttpStatus.OK))
.switchIfEmpty(getCustomResponse(id, result, HttpStatus.NOT_FOUND));