I’m trying to have Spring return a HTTP status using only @ResponseStatus directly on my custom exception like so:
@ResponseStatus(code = HttpStatus.EXPECTATION_FAILED)
public class UserAlreadyExistsException extends RuntimeException {
public UserAlreadyExistsException(final String email) {
super(String.format("User with email=%s already exists", email));
}
}
But it doesn’t work, it always returns a 403. Whereas when I add a handler method in a ControllerAdvice it works as desired:
@ControllerAdvice
public class GlobalExceptionHandler {
@ResponseStatus(code = HttpStatus.EXPECTATION_FAILED)
@ExceptionHandler(UserAlreadyExistsException.class)
public void handleUserAlreadyExistsException(UserAlreadyExistsException e) {
}
}
I don’t understand why. I also tried to remove the controller completely thinking its presence might interfere in the catching of the exception but it doesn’t work either.