menu 李昊天的个人博客
全局异常处理
723 浏览 | 2021-04-05 | 分类:SpringBoot | 标签:项目经验

这是一个前后端分离的项目,所以都是返回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;
    }
}
知识共享署名-非商业性使用-相同方式共享 4.0 国际许可协议

发表评论

email
web

全部评论 (暂无评论)

info 还没有任何评论,你来说两句呐!