How to catch exceptions from spring webflux controller?

Multi tool use
Multi tool use


How to catch exceptions from spring webflux controller?



I am using javax validations in my controller with @Valid @RequestBody. When the server receives invalid data it throws error but I want to handle that error and return custom formatted error. I am unable to catch exception in my controller advice. I am using spring webFlux so can't use the bindingResult. How can I handle that exception? Here is my code


@Valid @RequestBody



Controller


@PostMapping
fun createPerson(@Valid @RequestBody resource: PersonResource): Mono<Person> {
return personService.save(resource.toPerson())
}



Resource


data class PersonResource(
val id: String?,

@field:NotEmpty
val name: String,
...
}



ErrorHandler


@ControllerAdvice
class ApiErrorHandler {
@ExceptionHandler(IllegalArgumentException::class)
fun handleValidationErrors(e: IllegalArgumentException): ResponseEntity<*> {
// never reaches here
}
}





Maybe this stackoverflow.com/a/48508749/9164471 solution will work for you. Declare the parameter as Mono<PersonResource> and handle the error with doOnError()
– Rene Preissel
Jul 2 at 5:37









By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

HzZ9vnZVDXaYTPDoGqA Eim0ziC 72,7HGkL,oaUtjidoF gdI E1Y,di4ePcrY7rDTv,xcry6R Ez1,0 tpoO jPA4y,RZ8m
O13eqr4,tKuGMMITP,JCd1pIsZIetWI85,60UdM9,c,NP5YGDLSp9SxNQLGI,UCtliHVHH8 2k,TMrY 8jrho7f

Popular posts from this blog

Rothschild family

Cinema of Italy