小编use*_*858的帖子

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

我正在使用@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" );      
}
Run Code Online (Sandbox Code Playgroud)

然后在@ControllerAdvice,我尝试使用@ExceptionHandler@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";
}
Run Code Online (Sandbox Code Playgroud)

@ExceptionHandler方法可以处理HttpServletResponse#sendError()调用吗?

java spring spring-mvc

5
推荐指数
1
解决办法
2936
查看次数

标签 统计

java ×1

spring ×1

spring-mvc ×1