1
votes

I am trying to make a condition, which if not satisfied, throw an exception. But I tried in many ways and without success.

My restcontroller:

@GetMapping(value = ["/{id}"])
    fun find(@PathVariable id: String): Mono<ResponseEntity<Mono<Person>>> {
        return ResponseEntity.ok().body(service.find(id)).toMono()
}

My service

override fun find(id: String): Mono<Person> {
        return repository.findById(id).doOnError { throw DataNotFound("Person not found")}
  }

If I enter an existing ID, it returns me a registered person. But if I enter a nonexistent ID, instead of throwing the exception, it returns me a 200 with empty body.

How do I solve this? Could anyone help?

2

2 Answers

1
votes

Try this:

@GetMapping(value = ["/{id}"])
fun find(@PathVariable id: String): Mono<ResponseEntity<?>> {
  service.find(id).map(person -> ResponseEntity.ok().body(person))
    .onErrorResume(DataNotFound.class, exception -> ResponseEntity.notFound())
}

fun find(id: String): Mono<Person> {
  repository.findById(id).onErrorMap(error -> new DataNotFound("Person not found"))
}

It returns OK response if a person exists and NOT_FOUND otherwise.

0
votes

Usually, in a more complex scenario, you want to do a translation from exceptions to some kind of error resource.

In this scenario, you will use the same response type for your method which handles the HTTP request. More precisely, in your case:

@GetMapping(value = ["/{id}"])
fun find(@PathVariable id: String): Mono<ResponseEntity<Mono<Person>>> {
    return ResponseEntity.ok().body(service.find(id)).toMono()
}

(this will remain as it is!)

And next, you will provide a so-called ControllerAdvice which can look in your case like in the following snippet:

@ControllerAdvice(assignableTypes = [YourRestController::class]
class ControllerAdvice {

   @ExceptionHandler
   fun handle(ex: DataNotFoundException): ResponseEntity<DataNotFoundErrorResource> {
      return ResponseEntity.status(HttpStatus.NOT_FOUND).body(DataNotFoundErrorResource.from(ex)
   }
}

Note: Be aware that I've not used a Kotlin compiler, but I've compiled it in my mind :) I hope that it will be ok!