SpringBoot配置全局异常学习笔记

1.在未配置全局异常之前:访问一个出现异常的接口

 @GetMapping("/testJson")
 Object testJson(){
       int a = 1 /0 ;
       return new User("wjl12333",11,"13563986965",new Date(),"10010");
 }

浏览器中访问/testJson返回接口如图所示:

2.创建RestExceptonHandler

@RestControllerAdvice
public class RestExceptonHandler {

    @ExceptionHandler(Exception.class)
    Object handlerRestException(Exception e, HttpServletRequest request){
        Map<String,Object> map = new HashMap<>();
        map.put("code",100);
        map.put("msg",e.getMessage());
        map.put("url",request.getRequestURL());
        return  map;
    }

}

再次访问/testJson,返回结果如图所示:

3.配置自定义全局异常

创建自定义异常类

/**
 * @author LONG
 * 自定义全局异常
 */
public class MyException extends RuntimeException {
    private String code;

    private String msg;

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

    public String getCode() {
        return code;
    }

    public void setCode(String code) {
        this.code = code;
    }

    public String getMsg() {
        return msg;
    }

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

在RestExceptonHandler中添加对自定义异常的处理

@ExceptionHandler(MyException.class)
Object handlerMyException(MyException e, HttpServletRequest request){
   //返回跳转的错误提示界面
     /* ModelAndView mv = new ModelAndView();
        mv.addObject("error.html");
        return mv;*/
  //返回json数据由前端去判断加载什么页面
   logger.error("url {}, msg {}",request.getRequestURL(),e.getMsg());
   Map<String,Object> map = new HashMap<>();
   map.put("code",e.getCode());
   map.put("msg",e.getMsg());
   map.put("url",request.getRequestURL());
   return  map;
}

对自定义异常进行测试

 @GetMapping("/testMyException")
 Object testMyException(){
        throw new MyException("202","我自己定义的异常");
 }

返回结果

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值