I have 2 exception handler classes annotated with @RestControllerAdvice
and:
I use the first one as global exception handler to catch exceptions:
@RestControllerAdvice
public class GlobalExceptionHandler extends ResponseEntityExceptionHandler {
@Override
@ResponseStatus(HttpStatus.UNPROCESSABLE_ENTITY)
protected ResponseEntity<Object> handleMethodArgumentNotValid(...) {
// ...
}
@ExceptionHandler(Exception.class)
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
public ResponseEntity<Object> handleAllUncaughtException(Exception ex, WebRequest request) {
// ...
}
// code omitted for clarity
}
and the second for validation exceptions (I creates custom validation):
@RestControllerAdvice
public class ValidationExceptionHandler { // did not extend from extends ResponseEntityExceptionHandler
@ExceptionHandler(ConstraintViolationException.class)
@ResponseStatus(HttpStatus.UNPROCESSABLE_ENTITY)
protected ValidationErrorResponse onConstraintValidationException(ConstraintViolationException e) {
// ...
}
}
When I move onConstraintValidationException
to GlobalExceptionHandler
class, I catch validation exception and display corresponding message. But when it is in the second ControllerAdvice class (ValidationExceptionHandler
) as shown above, code does not hit onConstraintValidationException
method.
I also tried to extend the second class from ResponseEntityExceptionHandler
, but does not make any sense.
So, what is the problem and how can I fix it?