@ControllerAdvice
class GlobalExceptionHandler {
@ExceptionHandler(TypeMismatchException::class)
fun handleTypeMismatchException(e: TypeMismatchException): HttpStatus {
throw ResponseStatusException(HttpStatus.BAD_REQUEST, "Invalid value '${e.value}'", e)
}
@ExceptionHandler(WebExchangeBindException::class)
fun handleWebExchangeBindException(e: WebExchangeBindException): HttpStatus {
throw object : WebExchangeBindException(e.methodParameter!!, e.bindingResult) {
override val message = "${fieldError?.field} has invalid value '${fieldError?.rejectedValue}'"
}
}
}
SUMMARY:
"... exception handling is rather complicated and you could start interfering at many levels, which are from top to bottom:
Directly in the Controller with try/catch (MVC) or onErrorResume() (Webflux). I do not recommend this in most cases, because a cross-cutting concern like exception handling should be defined globally to guarantee a consistent behavior.
Intercept exceptions in @ExceptionHandler functions. Create your own responses, with @ExceptionHandler(Throwable.class) for the default case.
Or rethrow the exceptions, annotate them with @ResponseStatus or extend ResponseStatusException to customize the response for certain cases. ..."
Move exceptionHandler there https://medium.com/sprang/validation-and-exception-handling-with-spring-ba44b3ee0723
example:
SUMMARY: "... exception handling is rather complicated and you could start interfering at many levels, which are from top to bottom: