🌷1. 自定義一個異常類
自定義一個異常,有兩個變量異常代碼、異常消息,定義了兩個構造方法,一個無參構造方法,一個所有參數構造方法。
在構造方法中要掉用父類的構造方法,主要目的是在日志或控制臺打印異常的堆棧信息時,要把自己傳的異常消息打印出來。
@Getter
@Setter
public class MyException extends RuntimeException {private String errorCode;private String errorMessage;public MyException () {super();}public MyException(String errorCode, String errorMessage) {super(errorMessage);this.errorCode = errorCode;this.errorMessage = errorMessage;}}
🌹2.全局異常處理
全局異常處理需要兩個注解:
@RestControllerAdvice
:定義全局異常處理器是@ControllerAdvice
和@ResponseBody
的結合體。
@ExceptionHandler
:用于捕獲異常并處理
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {@ExceptionHandler(value = MyException.class)public Object restErrorHandler(HttpServletRequest request, MyException e) {log.error("報錯了:", e);return "錯誤碼:" + e.getErrorCode() + "錯誤內容:" + e.getErrorMessage();}
}
🌺3.使用
@RestController
public class TestController {@GetMapping("/exception")public void testException () {throw new MyException("500", "測試");}
}