How to Catch Exceptions from Spring Webflux Controller?

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

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
  }
}
1

1 Answer

I think you are catching a different exception. I am using @ControllerAdvice to catch WebExchangeBindException as validation errors and it worked for me.

A specialization of ServerWebInputException thrown when after data binding and validation failure. Implements BindingResult (and its super-interface Errors) to allow for direct analysis of binding and validation errors.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Marcus Vance
Author

Marcus Vance

Marcus Vance is a cybersecurity auditor and technology writer dedicated to educating the public about online safety, data privacy regulations, enterprise security, and emerging cyber threats.