Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring Exception Handling - @ControllerAdvice cannot handle HttpServletResponse#sendError()

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?

like image 292
user44858 Avatar asked Nov 11 '22 04:11

user44858


1 Answers

Spring Security is a separate framework from Spring MVC. Spring Security is a Servlet filter (have a look in your web.xml) which intercepts requests before they reach Spring MVC. You cannot process exceptions that happen at the Spring Security level in @ControllerAdvice (as @ControllerAdvice is part of Spring MVC).

As you said it yourself, HttpServletResponse#sendError() does not throw an exception. According to this document, it sends an error response to the client using the specified status code and clears the buffer.

In your web.xml file you can define static web pages (1) for error response codes and (2) for exceptions. For example:

<error-page>
    <error-code>401</error-code>
    <location>/errors/genericerror</location>
</error-page>
like image 154
Alexey Avatar answered Nov 15 '22 09:11

Alexey