目录
使用统一返回结果时,还有一种情况,就是程序的报错是由于运行时异常导致的结果,有些异常是我们在业务中抛出的,有些是无法提前预知。
因此,我们需要定义一个统一的全局异常,在Controller捕获所有异常,并且做适当处理,并作为一种结果返回。
一.创建一个异常类用于捕获针对项目或业务的异常
public class BusinessException extends RuntimeException {
private Integer code;
private String msg;
public BusinessException(ExceptionResponse response) {
super(response.getMsg());
this.msg = response.getMsg();
this.code = response.getCode();
}
public Integer getCode() {
return code;
}
public String getMsg() {
return msg;
}
}
二.使用@ExceptionHandler注解捕获自定义异常和通用异常
@ExceptionHandler(value = BusinessException.class)
public AjaxResult businessException(BusinessException e) {
log.error("BusinessException:{}", e);
return new AjaxResult(e.getMsg(), e.getCode());
}
三.使用@RestControllerAdvice集成@ExceptionHandler的方法到一个类中
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {
@ExceptionHandler(value = BusinessException.class)
public AjaxResult businessException(BusinessException e) {
log.error("BusinessException:{}", e);
return new AjaxResult(e.getMsg(), e.getCode());
}
@ExceptionHandler(value = Exception.class)
public AjaxResult exceptionHandler(Exception e) {
log.error("Exception:{}", e);
return new AjaxResult(e.getMessage(), BaseExceptionResponseEnum.SYSTEMBUSY.getCode());
}
}
四.异常的对象信息补充到统一结果枚举中
public enum BaseExceptionResponseEnum implements ExceptionResponse {
NOTOKEN(702, "没有Token"),
REFRESHTOKEN(703, "刷新Token"),
USERHASLOGOUT(704, "用户已登出"),
NOUSER(705, "没有该用户"),
PASSWORDERROR(706, "密码错误"),
LOGOUTSUCCESS(707, "登录成功"),
SYSTEMBUSY(708, "系统繁忙")
;
private Integer code;
private String msg;
BaseExceptionResponseEnum(Integer code, String msg) {
this.code = code;
this.msg = msg;
}
@Override
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
@Override
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
}