Springboot2.0全局异常捕捉处理和自定义全局异常处理

参考:https://blog.csdn.net/qq_22860341/article/details/81222379

https://www.cnblogs.com/magicalSam/p/7198420.html

自定义异常处理(全局异常处理)

1、编写自定义异常类:

/**
 * @description:统一异常处理
 * @author: Administrator
 * @date: 2019-03-28 11:16
 */
public class MyException extends RuntimeException{
    private Integer code;

    private String msg;

    public MyException(){

    }

    public MyException(String msg){

        super(msg);

    }


    public MyException(Integer code,String msg){

        super(msg);

        this.code=code;
        this.msg=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;
    }
}

2、编写全局异常处理类

/**
 * @description: controller 增强器
 * @author: Administrator
 * @date: 2019-04-12 09:08
 */
@ControllerAdvice
public class MyControllerAdvice {

    public static Log log = LogFactory.getLog(MyControllerAdvice.class);
    /**
     * 全局异常捕捉处理
     * @param ex
     * @return
     */
    @ResponseBody
    @ExceptionHandler(value = Exception.class)
    public Map errorHandler(Exception ex) {
        Map map = new HashMap();
        map.put("code", 100);
        map.put("msg", ex.getMessage());
        return map;
    }
    /**
     * 拦截捕捉自定义异常 MyException.class
     * @param ex
     * @return
     */
    @ResponseBody
    @ExceptionHandler(value = MyException.class)
    public Map myErrorHandler(MyException ex) {
        Map map = new HashMap();
        map.put("code", ex.getCode());
        map.put("msg", ex.getMsg());
        return map;
    }
}

3、controller中抛出异常进行测试。

/**
 * @description: 异常测试
 * @author: Administrator
 * @date: 2019-03-28 11:26
 */
@RestController
@RequestMapping("/ceshi")
public class ExceptionController {

    @GetMapping("/a")
    public AppResult<String> findall(String aa){
        if (aa==null){
            throw new MyException(4002,"测试错误");
//            return AppResultBuilder.success("测试错误", ResultCode.SUCCESS);
        }

        return AppResultBuilder.success("测试", ResultCode.SUCCESS);
    }
}

4.测试:

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值