1.之前处理工程异常,代码中最常见的就是try-catch-finally,有时一个try,多个catch,覆盖了核心业务逻辑,现在使用
Spring能够较好的处理这种问题,核心如下,文章主要关注前两个:
- @ExceptionHandler:统一处理某一类异常,从而能够减少代码重复率和复杂度
- @ControllerAdvice:异常集中处理,更好的使业务逻辑与异常处理剥离开
@ControllerAdvice
@RestController
public class CommonExceptionHandler {
/**
* Java一般异常
* @param e
* @return
*/
@ExceptionHandler(Exception.class)
@ResponseBody
public String exceptionHandler(Exception e){
e.printStackTrace();
if(e instanceof BindException){
int index = e.getMessage().lastIndexOf("[");
return Result.defeatedResultByCodeAndMsg(2, index!= -1?e.getMessage().substring(index + 1,e.getMessage().length()-1).trim():e.getMessage());
}
return Result.defeatedResultByMsg(e.toString());
}
/**
* 拦截自定义异常
* @param ex
* @return
*/
@ExceptionHandler(BaseException.class)
@ResponseBody
public String exceptionHandler(BaseException ex){
ex.printStackTrace();
if(ex.getCode()==null){
ex.setCode(4);
}
return Result.defeatedResultByCodeAndMsg(ex.getCode(),ex.getMsg());
}
}
2.自定义一个异常
public class BaseException extends RuntimeException{
private Integer code;
private String msg;
/**
* 默认异常,状态码为2
* @param msg
*/
public BaseException(String msg){
super();
this.msg=msg;
this.code=2;
}
/**
* 自定义异常
* @param code
* @param massge
*/
public BaseException(Integer code,String massge){
super(massge);
this.msg=msg;
this.code=code;
}
public BaseException(){
super("系统错误,请联系管理员");
this.code=4;
this.msg="系统错误,请联系管理员";
}
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
}