三:SpringBoot-配置系統全局異常映射處理
1、異常分類
這裏的異常分類從系統處理異常的角度看,主要分類兩類:業務異常和系統異常。
1。1 業務異常
業務異常主要是一些可預見性異常,處理業務異常,用來提示用戶的操作,提高系統的可操作性。
常見的業務異常提示:
- 請輸入xxx
- xxx不能爲空
- xxx重複,請更換
1.2 系統異常
系統異常主要是一些不可預見性異常,處理系統異常,可以讓展示出一個友好的用戶界面,不易給用戶造成反感。如果是一個金融類系統,在用戶界面出現一個系統異常的崩潰界面。
常見的系統異常提示:
- 頁面丟失404
- 服務器異常500
2、自定義異常處理
2.1 自定義業務異常類
public class ServiceException extends Exception {
public ServiceException (String msg){
super(msg);
}
}
2.2 自定義異常描述對象
public class ReturnException {
// 響應碼
private Integer code;
// 異常描述
private String msg;
// 請求的Url
private String url;
// 省略 get set 方法
}
2.3 統一異常處理格式
1.兩個基礎註解
- @ControllerAdvice 定義統一的異常處理類
- @ExceptionHandler 定義異常類型對應的處理方式
2.代碼實現
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
@ControllerAdvice
// 異常以Json格式返回 等同 ExceptionHandler + ResponseBody 註解
// @RestControllerAdvice
public class HandlerException {
/**
* 自定義業務異常映射,返回JSON格式提示
*/
@ExceptionHandler(value = ServiceException.class)
@ResponseBody
public ReturnException handler01 (HttpServletRequest request,ServiceException e){
ReturnException returnException = new ReturnException() ;
returnException.setCode(600);
returnException.setMsg(e.getMessage());
returnException.setUrl(String.valueOf(request.getRequestURL()));
return returnException ;
}
/**
* 服務異常
*/
@ExceptionHandler(value = Exception.class)
public ModelAndView handler02 (HttpServletRequest request,Exception e){
ModelAndView modelAndView = new ModelAndView() ;
modelAndView.addObject("ExeMsg", e.getMessage());
modelAndView.addObject("ReqUrl", request.getRequestURL());
modelAndView.setViewName("/exemsg");
return modelAndView ;
}
}
2.4 簡單的測試接口
@Controller
public class ExeController {
/**
* {
* "code": 600,
* "msg": "業務異常:ID 不能爲空",
* "url": "http://localhost:8003/exception01"
* }
*/
@RequestMapping("/exception01")
public String exception01 () throws ServiceException {
throw new ServiceException("業務異常:ID 不能爲空");
}
@RequestMapping("/exception02")
public String exception02 () throws Exception {
throw new Exception("出現異常,全體臥倒");
}
}