I'm using @ControllerAdvice
to implement a global exception handler but I got some issues with the use of HttpServletResponse#sendError()
method.
@ExceptionHandler
can catch all kinds of exception, but not HttpServletResponse#sendError()
invocations. I understand that HttpServletResponse#sendError()
is not an exception, but I need to process it, and then redirect to a generic error page.
I'm using Spring Security for authentication, and in the failed handler, I set status 401
to the response:
@Override
public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
String contentType = request.getContentType();
logger.info(contentType);
response.sendError( HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized" );
}
Then in the @ControllerAdvice
, I tried to use @ExceptionHandler
and @ResponseStatus
to catch 401
but it does not work:
@ResponseStatus (value=HttpStatus.UNAUTHORIZED, reason="You don't have access right on this page")//401
@ResponseBody
@ExceptionHandler(DataIntegrityViolationException.class)
public String handleHttpStatus(DataIntegrityViolationException e){
return "genericerror";
}
Can @ExceptionHandler
methods process HttpServletResponse#sendError()
invocations?