博主原創,未經允許不得轉載:
每個項目都有自己的一套異常類的定義。總結一下,項目中使用自定義異常比較好的封裝。
1.定義項目中統一使用的異常類,用於捕獲項目中的自定義異常等:
package com.common; /** * 自定義異常 */ public class CustomException extends Exception { private static final long serialVersionUID = 8984728932846627819L; public CustomException() { super(); } public CustomException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { super(message, cause, enableSuppression, writableStackTrace); } /** * @param message * @param cause */ public CustomException(String message, Throwable cause) { super(message, cause); } /** * @param message */ public CustomException(String message) { super(message); } /** * @param cause */ public CustomException(Throwable cause) { super(cause); } }
2.定義異常捕獲后返回給客戶端的統一數據格式的實體類:
@Data public class ErrorResult{ // 錯誤碼 private Integer errorCode; // 錯誤描述 private String errorMsg; }
3.使用 @RestControllerAdvice注解,自定義異常捕獲的基類,處理和封裝捕獲的異常信息。
看 @RestControllerAdvice 源碼可以知道,它就是@ControllerAdvice和@ResponseBody的合並。此注解通過對異常的攔截實現的統一異常返回處理。
它通常用於定義@ExceptionHandler, @InitBinder 和 @ModelAttribute 適用於所有@RequestMapping方法的方法。
創建一個 GlobalExceptionHandler
類,並添加上 @RestControllerAdvice
注解就可以定義出異常通知類了,然后在定義的方法中添加上 @ExceptionHandler
即可實現異常的捕捉
import com.baizhi.exception.CustomException; import com.baizhi.exception.ErrorResult; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.MethodArgumentNotValidException; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.RestControllerAdvice; import org.springframework.web.context.request.WebRequest; import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @RestControllerAdvice public class GlobalExceptionHandler{ /** * 定義要捕獲的異常 可以多個 @ExceptionHandler({}) * * @param request request * @param e exception * @param response response * @return 響應結果 */ @ExceptionHandler(CustomException.class) public ErrorResult customExceptionHandler(HttpServletRequest request, final Exception e, HttpServletResponse response) { response.setStatus(HttpStatus.BAD_REQUEST.value()); CustomException exception = (CustomException) e; return new ErrorResult(exception.getCode(), exception.getMessage()); } /** * 捕獲 RuntimeException 異常 * TODO 如果你覺得在一個 exceptionHandler 通過 if (e instanceof xxxException) 太麻煩 * TODO 那么你還可以自己寫多個不同的 exceptionHandler 處理不同異常 * * @param request request * @param e exception * @param response response * @return 響應結果 */ @ExceptionHandler(RuntimeException.class) public ErrorResult runtimeExceptionHandler(HttpServletRequest request, final Exception e, HttpServletResponse response) { response.setStatus(HttpStatus.BAD_REQUEST.value()); RuntimeException exception = (RuntimeException) e; return new ErrorResult(400, exception.getMessage()); } }