spring-boot,全局异常统一拦截处理

外链:访问地址
1、创建自定义的异常RRException
package com.blog.common.utils;

/**
 * @author wangfj
 * @date 2018-11-19
 * @description 自定义异常
 */
public class RRException extends RuntimeException {
    private static final long serialVersionUID = 1L;

    private String msg;
    private int code = 500;
    private Object data;

    public Object getData() {
        return data;
    }

    public void setData(Object data) {
        this.data = data;
    }

    public RRException(String msg) {
        super(msg);
        this.msg = msg;
    }

    public RRException(String msg, Throwable e) {
        super(msg, e);
        this.msg = msg;
    }

    public RRException(String msg, int code) {
        super(msg);
        this.msg = msg;
        this.code = code;
    }

    public RRException(String msg, int code, Throwable e) {
        super(msg, e);
        this.msg = msg;
        this.code = code;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public int getCode() {
        return code;
    }

    public void setCode(int code) {
        this.code = code;
    }
}
2、创建异常处理配置类MyExceptionHandler
package com.blog.index.config;

import com.blog.common.result.R;
import com.blog.common.utils.RRException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @author wangfujie
 * @date 2018-12-12 16:45
 * @description 全局异常捕获处理
 */
@ControllerAdvice
public class MyExceptionHandler {

    /**
     * 统一异常处理
     * @param e
     * @return
     */
    @ResponseBody
    @ExceptionHandler(value = Exception.class)
    public Object errorHandler(Exception e){
        e.printStackTrace();
        return R.error(110, e.getMessage());
    }

    /**
     * 自定义异常的处理
     * @param e
     * @return
     */
    @ResponseBody
    @ExceptionHandler(value = RRException.class)
    public Object myErrorHandler(RRException e){
        e.printStackTrace();
        return R.error(e.getCode(), e.getMsg());
    }
}
3、在代码中手动抛出异常即可
throw new RRException("该用户没有权限!", 504);
4、返回效果
{"msg":"该用户没有权限!","code":504,"needRefresh":true}

在这里插入图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值