springboot异常处理 -自我整理笔记

在这里插入图片描述

如何定制错误页面

能自定义json数据也能自适应(自适应:postman是json 浏览器是web页面)
核心是: 自定义ErrorAttributes
原理:返回HTML的方法和json的方法都是使用了getErrorAttributes方法,因此我们只需要重写此方法加上自定义的json就可以了
分析:
根据处理机制查看源码BasicErrorController,发现html 和 json 都是经过getErrorAttributes得到的
在这里插入图片描述跳转到getErrorAttributes,发现是errorAttributes(接口)实现的,
在这里插入图片描述ctrl+h找到实现类,发现了DefaultErrorAttributes
在这里插入图片描述因此我们只需要继承DefaultErrorAttributes,改写其中方法就可以了

完整实例
自定义异常类

public class UserNotFoundException extends RuntimeException {
    public UserNotFoundException() {
        super("用户不存在");
    }
}

异常处理类

@ControllerAdvice
public class MyExceptionHandler {
    @ExceptionHandler(UserNotFoundException.class)
    public String handleException(Exception e, HttpServletRequest request){
        Map<String,Object> map = new HashMap<>();
        //传入我们自己的错误状态码 4xx 5xx,否则就不会进入定制错误页面的解析流程
        //源码展示: Integer statusCode = (Integer) request.getAttribute("javax.servlet.error.status_code");
        request.setAttribute("javax.servlet.error.status_code",500);
        map.put("code","user.notexist");
        map.put("message",e.getMessage());
        request.setAttribute("ext",map); //这两个数据就会传递给MyErrorAttributes处理器
        //转发到/error
        return "forward:/error";
    }
}

继承DefaultErrorAttributes重写方法类 (代码中0 的含义)

@Component
public class MyErrorAttributes extends DefaultErrorAttributes {
    @Override
    public Map<String, Object> getErrorAttributes(WebRequest webRequest, boolean includeStackTrace) {
       Map<String,Object> map =  super.getErrorAttributes(webRequest, includeStackTrace);
       map.put("company","leileileilei");
       Map<String,Object> ext = (Map<String,Object>)webRequest.getAttribute("ext",0);
       map.put("ext",ext);
       return map;
    }
    public MyErrorAttributes(ServerProperties serverProperties) {
        super(serverProperties.getError().isIncludeException());
    }
}

前端

<main role="main" class="col-md-9 ml-sm-auto col-lg-10 pt-3 px-4">
   <h1>status:[[${status}]]</h1>
   <h2>timestamp:[[${timestamp}]]</h2>
   <h2>exception:[[${exception}]]</h2>
   <h2>message:[[${message}]]</h2>
   <h2>ext:[[${ext.code}]]</h2>
   <h2>ext:[[${ext.message}]]</h2>
</main>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值