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