Spring的全局異常,用於捕獲程序員沒有捕獲的異常。具體請看下面代碼:程序員
1.ControllerAdvice攔截異常,統一處理.經過Spring的AOP來管理.框架
@ControllerAdvice
public class ExceptionHandle {
/**
* 要捕獲什麼異常:
* @return 返回Result:
*/
@ExceptionHandler(value = Exception.class)
@ResponseBody
public Result handle(Exception e){
e.printStackTrace();
if(e instanceof MyException){
MyException myException = (MyException)e;
return ResultUtil.error(myException.getCode(),myException.getMessage());
}else{
return ResultUtil.error(-1,"系統錯誤,請聯繫程序員");
}
}
}this
/**
* 自定義異常類,由於Exception拋出只能夠傳消息,太不方便了.
* 提示:RuntimeException, 源碼:RuntimeException extends Exception
* 而且Spring框架對RuntimeException纔會回滾.Exception不會回滾.
* create by xxx編碼
* 2019-05-26
*/
public class MyException extends RuntimeException {
private Integer code;
public MyException(ResultEnum resultEnum){
super(resultEnum.getMsg());//父類能夠穿個msg,Service層能夠拋出MyException.
this.code = resultEnum.getCode();
}
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
}spa
/**
* created by : xxxcode
* 2019-05-27
*/
public enum ResultEnum {
UNCO_ERROR(-1,"未知錯誤"),
SUCCESS(0,"成功")
;
/**
* 編碼:
*/
private Integer code;
/**
* 消息:
*/
private String msg;
ResultEnum(Integer code,String msg){
this.code = code;
this.msg = msg;
}
public Integer getCode() {
return code;
}
public String getMsg() {
return msg;
}
}get