首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 綜合教學

Spring 4 異常處理體系:HTTP 狀態碼映射、@ExceptionHandler 與 @ControllerAdvice 全局統一處理

     編輯:Java 綜合教學

1. 異常自動映射 HTTP 狀態碼(@ResponseStatus)

Spring 內置將常見異常映射為合適狀態碼:

  • TypeMismatchException(參數類型不匹配) → 400 Bad Request
  • HttpRequestMethodNotSupportedException → 405
  • HttpMediaTypeNotSupportedException → 415
  • MissingServletRequestParameterException → 400
  • 其他未映射異常 → 500 Internal Server Error

異常映射表

實例:傳入 long 參數值 "2l" 拋出 TypeMismatchException,前端收到 400 狀態碼。
400響應截圖

2. 自定義異常綁定狀態碼

@ResponseStatus(value = HttpStatus.NOT_FOUND)
public class MyException extends RuntimeException { }

Controller 拋出 throw new MyException(),響應自動帶上 404 狀態碼。

3. 控制器級異常處理(@ExceptionHandler)

僅處理同一 Controller 內拋出的異常:

@ExceptionHandler(MyException.class)
@ResponseBody
public String handleMyException() {
    return "handle by ExceptionHandler.";
}

瀏覽器直接顯示返回字符串,狀態碼為 200(除非配合 @ResponseStatus)。

4. 全局異常處理(@ControllerAdvice)—— 生產環境標配

統一處理所有 Controller拋出的異常:

@ControllerAdvice
public class GlobalExceptionHandler extends BaseController {
    private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    @ExceptionHandler(Exception.class)
    @ResponseBody
    public String handleException(HttpServletRequest request, Exception e) {
        logger.error("Request FAILD, URL = {}", request.getRequestURI(), e);
        return gson.toJson(BaseController.FAILD);
    }

    @ExceptionHandler(NumberFormatException.class)
    @ResponseBody
    public String handleNumberFormatException(HttpServletRequest request, NumberFormatException e) {
        logger.error("Request FAILD, URL = {}", request.getRequestURI(), e);
        return gson.toJson(BaseController.FAILD);
    }
}

關鍵點:組件掃描需包含 @ControllerAdvice

<!-- spring-mvc.xml -->
<context:component-scan base-package="com.cetiti.epdc.dss">
    <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    <context:include-filter type="annotation" expression="org.springframework.web.bind.annotation.ControllerAdvice"/>
</context:component-scan>

<!-- spring.xml (業務層掃描排除 Web 註解) -->
<context:component-scan base-package="com.cetiti.epdc.dss">
    <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    <context:exclude-filter type="annotation" expression="org.springframework.web.bind.annotation.ControllerAdvice"/>
</context:component-scan>

異常匹配優先級

子類異常優於父類,NumberFormatException 比 Exception 先匹配,精準處理更靈活。

5. 總結最佳實踐

  1. 業務自定義異常加 @ResponseStatus 明確語義化 HTTP 碼;
  2. 全局統一用 @ControllerAdvice + @ExceptionHandler,返回統一 JSON 結構(code/msg/data);
  3. 區分業務異常(已知可控)與系統異常(未知錯誤),前者返回 4xx,後者 5xx 並告警;
  4. 異常日誌務必打印完整堆棧與請求上下文(URL、參數、用戶),便於排查。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved