Enrico-git / WA2-EGLR

Laboratories and project of Web Application 2
0 stars 0 forks source link

@ControllerAdvice #2

Closed Enrico-git closed 3 years ago

Enrico-git commented 3 years ago

Move exceptionHandler there https://medium.com/sprang/validation-and-exception-handling-with-spring-ba44b3ee0723

example:

@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:

  1. 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.
  2. Intercept exceptions in @ExceptionHandler functions. Create your own responses, with @ExceptionHandler(Throwable.class) for the default case.
  3. Or rethrow the exceptions, annotate them with @ResponseStatus or extend ResponseStatusException to customize the response for certain cases. ..."