Spring 內置將常見異常映射為合適狀態碼:
TypeMismatchException(參數類型不匹配) → 400 Bad RequestHttpRequestMethodNotSupportedException → 405HttpMediaTypeNotSupportedException → 415MissingServletRequestParameterException → 400
實例:傳入 long 參數值 "2l" 拋出 TypeMismatchException,前端收到 400 狀態碼。

@ResponseStatus(value = HttpStatus.NOT_FOUND)
public class MyException extends RuntimeException { }
Controller 拋出 throw new MyException(),響應自動帶上 404 狀態碼。
僅處理同一 Controller 內拋出的異常:
@ExceptionHandler(MyException.class)
@ResponseBody
public String handleMyException() {
return "handle by ExceptionHandler.";
}
瀏覽器直接顯示返回字符串,狀態碼為 200(除非配合 @ResponseStatus)。
統一處理所有 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);
}
}
<!-- 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 先匹配,精準處理更靈活。
@ResponseStatus 明確語義化 HTTP 碼;@ControllerAdvice + @ExceptionHandler,返回統一 JSON 結構(code/msg/data);