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,"系统错误,请联系程序员");
}
}
}
- 因为原来的Exception只可以传msg,那么我们就可以自定义自己的异常,可以传code:
/**
* 自定义异常类,因为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;
}
}
- 因为现在的项目有一些会返回code信息,但是随手定义一个不好维护,我们可以定义成枚举类型,对这些code,msg进行统一管理.
/**
* created by : xxx
* 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;
}
}