侧边栏壁纸
博主头像
昊天的个人博客 博主等级

行动起来,活在当下

  • 累计撰写 65 篇文章
  • 累计创建 72 个标签
  • 累计收到 0 条评论

目 录CONTENT

文章目录

全局异常处理

昊天
2021-04-05 / 0 评论 / 0 点赞 / 2 阅读 / 0 字

这是一个前后端分离的项目,所以都是返回BaseResult,BaseResult的数据结构参照上一篇博客,非前后端分离的可以把请求发送到错误页,效果一样。 如果有其他异常需要单独处理,加方法就行,方法上面用@ExceptionHandler标注上就可以。

使用 @ControllerAdvice 标注上全局异常处理类



@ControllerAdvice
public class AllExceptionHandler {

    // 最高级的异常,拦截所有
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public BaseResult exceptionHandler(Exception e) {
        e.printStackTrace();
        return new BaseResult(400, e.getMessage(), null);
    }


    //校验异常
    @ExceptionHandler(BindException.class)
    @ResponseBody
    public BaseResult bindExceptionHandler(BindException e) {
        BindingResult exceptions = e.getBindingResult();
        // 判断异常中是否有错误信息,如果存在就使用异常中的消息,否则使用默认消息
        if (exceptions.hasErrors()) {
            List<ObjectError> errors = exceptions.getAllErrors();
            if (!errors.isEmpty()) {
                // 这里列出了全部错误参数,按正常逻辑,只需要第一条错误即可
                FieldError fieldError = (FieldError) errors.get(0);
                return new BaseResult(Code.PARAMETER_ERROR).setMsg(fieldError.getDefaultMessage());

            }
        }
        return new BaseResult(Code.PARAMETER_ERROR);
    }

    // 自定义异常
    @ExceptionHandler(BaseException.class)
    @ResponseBody
    public BaseResult exceptionMineHandler(BaseException e) {
        return new BaseResult(e.getCode(), e.getMsg(), null);
    }
}


BaseException


public class BaseException extends Exception{
    private Integer code;
    private String msg;

    public BaseException(Integer code, String msg) {
        this.code = code;
        this.msg = msg;
    }

    public BaseException() {
    }

    public BaseException(Code code) {
        this.code=code.getCode();
        this.msg= code.getMsg();
    }
    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;
    }
}
0

评论区