spring boot 全局異常處理
處理全局異常需要分爲三步來做
- 自定義異常枚舉
- 自定義異常
- spring boot AOP異常處理
下面我寫的比較簡單,希望結合根據自己情況處理,這裏就簡單的寫一些代碼思想
1 自定義一樣枚舉
public enum WebExceptionEnum {
/**
* SYS_ERROR 系統文件錯誤
* UNKNOWN_ERROR 未知系統錯誤
* SERVICE_INVOKE_ERROR 服務器調用錯誤
* ILLEGAL_ARGS 傳入參數不正確
*/
SYS_ERROR("SYS_ERROR", "系統錯誤請重試"),
UNKNOWN_ERROR("UNKNOWN_ERROR", "未知系統錯誤"),
SERVICE_INVOKE_ERROR("SERVICE_INVOKE_ERROR", "服務器調用錯誤"),
ILLEGAL_ARGS("ILLEGAL_ARGS", "參數效驗失敗");
private String exception;
private String massage;
WebExceptionEnum(String exception, String massage) {
this.exception = exception;
this.massage = massage;
}
public String getException() {
return exception;
}
public String getMassage() {
return massage;
}
public static WebExceptionEnum getWebException(String exception) {
for (WebExceptionEnum results : WebExceptionEnum.values()) {
if (results.getException().equals(exception)) {
return results;
}
}
return null;
}
}
2 自定義異常
public class MessageCenterException extends RuntimeException{
private static final long serialVersionUID = -8581672033133636908L;
//異常狀態枚舉類型
private WebExceptionEnum exceptionEnum;
//set方法
private void setExceptionEnum(WebExceptionEnum exceptionEnum){
this.exceptionEnum = exceptionEnum;
}
//無參構造方法
public WebExceptionEnum getExceptionEnum(){
return exceptionEnum;
}
//獲取枚舉異常信息
public MessageCenterException(WebExceptionEnum exceptionEnum){
super(exceptionEnum.getMassage());
this.setExceptionEnum(exceptionEnum);
}
//獲取異常信息
@Override
public String getMessage() {
return exceptionEnum.getMassage();
}
}
3 全局異常處理
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {
// 全局的錯誤的異常處理
//
/**
* oracle 存儲過程 維護
* 數據庫層異常
* 業務層的異常
*/
// value處理那個異常
@ExceptionHandler(MessageCenterException.class)
public Result baseException(HttpServletRequest request, MessageCenterException ex) {
log.error(ex.getMessage());
return ErrorResult.error(ex.getMessage());
}
}
之後再項目中就返回這個一樣,一般一個異常類就夠了,如果很複雜可以擴展