簡體   English   中英

Spring異常處理 - @ControllerAdvice無法處理HttpServletResponse#sendError()

[英]Spring Exception Handling - @ControllerAdvice cannot handle 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" );      
}

然后在@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";
}

@ExceptionHandler方法可以處理HttpServletResponse#sendError()調用嗎?

Spring Security是Spring MVC的獨立框架。 Spring Security是一個Servlet過濾器(在您的web.xml中查看),它在到達Spring MVC之前攔截請求。 您無法在@ControllerAdvice處理Spring Security級別發生的異常(因為@ControllerAdvice是Spring MVC的一部分)。

正如你自己所說, HttpServletResponse#sendError()不會拋出異常。 根據文檔,它sends an error response to the client using the specified status code and clears the buffer.

web.xml文件中,您可以為錯誤響應代碼定義靜態網頁(1),為(2)異常定義。 例如:

<error-page>
    <error-code>401</error-code>
    <location>/errors/genericerror</location>
</error-page>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM