春天反应 - 如何处理mono.error在调用方法

问题描述 投票:0回答:1

我是新来的春天数据反应卡桑德拉。在我服务类我正在对注射执行ReactiveCassandraRepository的返回我的POJO的单声道,如果它被赋予的ID找到它。

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

当资源库找到给定ID的记录上面的代码工作正常。但是,如果没有找到记录,然后我不知道发生了什么。我没有收到返回的任何异常任何日志。

上述的getResult方法由我的弹簧控制器调用。但我不知道如何在我的控制器处理,这样我可以把我的消费者相关回应。

下面给出的是我的控制器代码。

@RequestMapping(value = “/check/order/{id}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public Mono<ResponseEntity<MyPojo>> getResult(
        @PathVariable(“id") id id) {

    return myService.getResult(id)
            .flatMap(result -> result!=null ?
                    getCustomResponse(id, result,HttpStatus.OK) :
                    getCustomResponse(id,result, HttpStatus.INTERNAL_SERVER_ERROR));
}

我们如何在调用方法处理Mono.error()。

问候,

Vinoth

spring exception-handling mono spring-webflux reactive
1个回答
0
投票

看起来像你的资料库返回空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));
© www.soinside.com 2019 - 2024. All rights reserved.