在Spring Boot中,異常處理可以通過幾種方式實現,以提高應用程序的健壯性和用戶體驗。這些方法包括使用@ControllerAdvice
注解、@ExceptionHandler
注解、實現ErrorController
接口等。下面是一些實現Spring Boot異常處理的常用方法:
1. 使用@ControllerAdvice
和@ExceptionHandler
@ControllerAdvice
是一個用于全局異常處理的注解,它允許你在整個應用程序中處理異常,而不需要在每個@Controller
中重復相同的異常處理代碼。@ExceptionHandler
用于定義具體的異常處理方法。
@ControllerAdvice
public class GlobalExceptionHandler {@ExceptionHandler(value = Exception.class)public ResponseEntity<Object> handleGeneralException(Exception ex, WebRequest request) {Map<String, Object> body = new LinkedHashMap<>();body.put("timestamp", LocalDateTime.now());body.put("message", "An error occurred");return new ResponseEntity<>(body, HttpStatus.INTERNAL_SERVER_ERROR);}@ExceptionHandler(value = CustomException.class)public ResponseEntity<Object> handleCustomException(CustomException ex, WebRequest request) {Map<String, Object> body = new LinkedHashMap<>();body.put("timestamp", LocalDateTime.now());body.put("message", ex.getMessage());return new ResponseEntity<>(body, HttpStatus.BAD_REQUEST);}
}
2. 實現ErrorController
接口
如果你想自定義/error
路徑下的錯誤頁面或響應,可以通過實現Spring Boot的ErrorController
接口來實現。
@Controller
public class CustomErrorController implements ErrorController {@RequestMapping("/error")public String handleError(HttpServletRequest request) {// 可以獲取錯誤狀態碼和做其他邏輯處理Object status = request.getAttribute(RequestDispatcher.ERROR_STATUS_CODE);if (status != null) {int statusCode = Integer.parseInt(status.toString());// 根據狀態碼返回不同的視圖名或模型}return "errorPage"; // 返回錯誤頁面的視圖名}@Overridepublic String getErrorPath() {return "/error";}
}
3. ResponseEntityExceptionHandler
擴展
通過擴展ResponseEntityExceptionHandler
類,你可以覆蓋其中的方法來自定義處理特定的異常。這個類提供了一系列方法來處理Spring MVC拋出的常見異常。
@ControllerAdvice
public class CustomResponseEntityExceptionHandler extends ResponseEntityExceptionHandler {@Overrideprotected ResponseEntity<Object> handleMethodArgumentNotValid(MethodArgumentNotValidException ex,HttpHeaders headers, HttpStatus status, WebRequest request) {Map<String, Object> body = new LinkedHashMap<>();body.put("timestamp", LocalDateTime.now());body.put("status", status.value());List<String> errors = ex.getBindingResult().getFieldErrors().stream().map(x -> x.getDefaultMessage()).collect(Collectors.toList());body.put("errors", errors);return new ResponseEntity<>(body, HttpStatus.BAD_REQUEST);}// 其他異常處理...
}
通過這些方法,Spring Boot允許開發者靈活地處理應用程序中的異常,無論是全局處理還是特定異常的定制化處理,都能以優雅和統一的方式進行。