Springboot个人博客系统 2 异常处理

异常处理

处理异常时会用到三个错误页面分别为:

  • 404页面
  • 500页面
  • error页面

一.定义异常错误页面

在Springboot中遇到异常会自动跳到一个统一的异常页面,这意味着Springboot已经有一套处理异常的机制,我们只需要自己去定义该错误的页面。
SpringBoot 默认的异常处理机制:一旦程序中出现了异常 SpringBoot 就会请求 /error 的 url ,然后跳转到默认显示异常的页面来展示异常信息。接下来就是自定义异常错误页面了,方法很简单,就是在目录 src/main/resources/templates/ 下定义一个error文件夹,放入404.html,500.html就可以了。

文件结构:
在这里插入图片描述
这样当出现404,500错误时就会跳转

error页面定义

这里需要一个自定义异常类

@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注解,我们自定义的异常可以在页面上显示

下面需要一个拦截器

@ControllerAdvice
public class ControllerExceptionHandler {
    private Logger logger = LoggerFactory.getLogger(this.getClass());
    @ExceptionHandler(Exception.class)
    public ModelAndView exceptionHander(HttpServletRequest request, Exception e){
        logger.error("Request URL : {}, Exception : {} ", request.getRequestURL(), e);
        if(AnnotationUtils.findAnnotation(e.getClass(), ResponseStatus.class) != null){
            //通过注解工具类判断是否有状态码
            try {
                throw e;
            } catch (Exception e1) {
                e1.printStackTrace();
            }
        }
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("url", request.getRequestURL());
        modelAndView.addObject("exception", e);
        modelAndView.setViewName("error/error");
        return modelAndView;
    }
}

这里使用拦截器进行统一的异常处理,通过AnnotationUtils.findAnnotation()判断是否有状态吗,当存在状态码时,则抛出异常,不存在时则返回error页面

错误页面异常信息处理

 <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
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值