Search code examples
springexceptionmonospring-webfluxreactive

Spring reactive - how to handle mono.error in calling method


I am new to spring data reactive Cassandra. In my service class i am injecting on implementation of ReactiveCassandraRepository which returns Mono of my pojo if it finds it by given 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());
        }
}

The above code works fine when the repository finds a record for given id. But if the record not found then i am not sure what is happening. I am not getting any log which returns any exception.

The above getResult method is called by my spring controller. But i am not sure how to handle this in my controller so that i can send relevant response to my consumers.

Given below is my controller code.

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

How do we handle Mono.error() in calling method.

Regards,

Vinoth


Solution

  • Looks like your repository returns empty Mono when it can not find any record.

    You could change your getResult method:

    return myRepository.findById(id)
            .flatMap(result -> getDecision(result))
            .switchIfEmpty(Mono.error(new Exception("result not found for id: " + id)));
    

    Or better you could change your controller if you don't want to create the instance of any exception:

    return myService.getResult(id)
            .flatMap(result -> getCustomResponse(id, result, HttpStatus.OK))
            .switchIfEmpty(getCustomResponse(id, result, HttpStatus.NOT_FOUND));