SpringBoot--错误信息拦截

SpringBoot 默认的处理异常的机制:
       SpringBoot 默认的已经提供了一套处理异常的机制。 一旦程序中出现了异常 SpringBoot 会向 /error 的 url 发送请求。在 springBoot 中提供了一个叫BasicExceptionController 来处理 /error 请求,然后跳转到默认显示异常的页面来展示异常信息。
在这里插入图片描述自定义错误页面
       在Thymleaf模板引擎下,我们可以在template目录下创建一个error包存放错误页面,如404,500,error等HTML,SpringBoot会根据状态码跳转到相应页面。
在这里插入图片描述
控制器处理异常
       在handler包下新建异常控制器类:

@ControllerAdvice
public class ControllerExceptionHandler {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    //表明该方法可以做异常处理
    @ExceptionHandler(Exception.class)
    public ModelAndView exceptionHander(HttpServletRequest request, Exception e) throws Exception {
        logger.error("Requst URL : {},Exception : {}", request.getRequestURL(),e);

//        当标识了状态码的时候就不拦截
        if (AnnotationUtils.findAnnotation(e.getClass(), ResponseStatus.class) != null) {
            throw e;
        }

        ModelAndView mv = new ModelAndView();
        mv.addObject("url",request.getRequestURL());
        mv.addObject("exception", e);
        mv.setViewName("error/error");
        return mv;
    }
}

@ControllerAdvice注解:拦截所有带有Controller注解的控制器
@ExceptionHandler(Exception.class)注解:该方法可以做异常处理
ControllerExceptionHandler会在controllers前面统一拦截所有Exception,记录日志并跳转到错误页面。

自定义NotFoundException

@ResponseStatus(HttpStatus.NOT_FOUND)
public class NotFoundException extends RuntimeException{
    public NotFoundException() {
    }
    public NotFoundException(String message) {
        super(message);
    }
    public NotFoundException(String message, Throwable cause) {
        super(message, cause);
    }
}

@ResponseStatus注解:返回http状态码,这里值为HttpStatus.NOT_FOUND异常状态码
SpringBoot拿到异常状态码之后会找到对应状态码的404页面,这里要注意做一下逻辑判断,如果状态码不为空,异常控制器不进行拦截

在error.html错误页面使用Thymleaf提供的错误信息模板,在返回错误页面后方便通过查看网页源代码找打错误信息。

  <div>
    <div th:utext="'&lt;!--'" th:remove="tag"></div>
    <div th:utext="'Failed Request URL : ' + ${url}" th:remove="tag"></div>
    <div th:utext="'Exception message : ' + ${exception.message}" th:remove="tag"></div>
    <ul th:remove="tag">
      <li th:each="st : ${exception.stackTrace}" th:remove="tag"><span th:utext="${st}" th:remove="tag"></span></li>
    </ul>
    <div th:utext="'--&gt;'" th:remove="tag"></div>
  </div>
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值