Spring 异常处理 - @ControllerAdvice 无法处理 HttpServletResponse#sendError()

2024-01-03

我在用着@ControllerAdvice实现全局异常处理程序,但我在使用时遇到了一些问题HttpServletResponse#sendError()方法。@ExceptionHandler可以捕获各种异常,但不能HttpServletResponse#sendError()调用。我明白那个HttpServletResponse#sendError()不是例外,但我需要处理它,然后重定向到通用错误页面。

我使用 Spring Security 进行身份验证,并在失败的处理程序中设置状态401回复:

@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" );      
}

然后在@ControllerAdvice,我尝试使用@ExceptionHandler and @ResponseStatus去抓401但它不起作用:

@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方法过程HttpServletResponse#sendError()调用?


Spring Security 是一个独立于 Spring MVC 的框架。 Spring Security 是一个 Servlet 过滤器(看看你的web.xml)在请求到达 Spring MVC 之前拦截请求。您无法处理在 Spring Security 级别发生的异常@ControllerAdvice (as @ControllerAdvice是 Spring MVC 的一部分)。

正如你自己所说,HttpServletResponse#sendError()不会抛出异常。根据this http://docs.oracle.com/javaee/6/api/javax/servlet/http/HttpServletResponse.html文档,它sends an error response to the client using the specified status code and clears the buffer.

In your web.xml在该文件中,您可以定义静态网页 (1) 错误响应代码和 (2) 异常。例如:

<error-page>
    <error-code>401</error-code>
    <location>/errors/genericerror</location>
</error-page>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Spring 异常处理 - @ControllerAdvice 无法处理 HttpServletResponse#sendError() 的相关文章

随机推荐