您的位置:首页 > 教程文章 > 编程开发

SpringBoot配置GlobalExceptionHandler全局异常处理器案例

:0 :2021-10-22 18:20:10

1. 创建全局异常处理器类GlobalExceptionHandler
@ControllerAdvice: 定义统一的异常处理类,捕获 Controller 层抛出的异常。如果添加 @ResponseBody 返回信息则为JSON格式,这样就不必在每个Controller中逐个定义AOP去拦截处理异常。
@RestControllerAdvice: 相当于 @ControllerAdvice 与 @ResponseBody 的结合体。
@ExceptionHandler: 统一处理一种类的异常,减少代码重复率,降低复杂度。
@ControllerAdvice
public class GlobalExceptionHandler {
    //@ExceptionHandler 该注解声明异常处理方法,  ModelAndView mv
    @ExceptionHandler(value = Exception.class)
    public ModelAndView myHandler(Exception e, HttpServletRequest request, HttpServletResponse response) {
        System.out.println("GlobalExceptionHandler全局异常处理器捕获");
        ModelAndView mv = new ModelAndView();
        mv.addObject("message", e.getMessage());         //异常错误信息提示
        mv.addObject("url", request.getRequestURI());    //异常请求的url地址
        mv.addObject("status", response.getStatus());    //获取状态码
        mv.setViewName("/pages/exception/error");    //异常的视图名称
        return mv;
    }
}
【注意】基于@ControllerAdvice注解的全局异常统一处理只能针对于Controller层的异常。也就是只能捕获到Controller层的异常,在service层或者其他层面的异常都不能捕获。
2. 创建controller测试出现异常情况
    //测试异常处理
    @GetMapping(path = "/exception")
    public String toException() {
        System.out.println("toException");
        //throw new Exception();
        int i =1/0;
        System.out.println("toException end");
       
        return "/pages/company/company_list";
    }
编写html页面显示错误信息
<!-- 统一异常处理页面 -->
<!DOCTYPE html>
<html xmlns:th=" >
<head>
 <title>出现错误啦</title>
</head>
<body>
<div class="content-container">
    <div class="head-line">
        <img src="../img/error.jpg" alt="" width="120"/>
    </div>
    <div class="subheader">
        <span name="message" th:text="${status}"/>,页面走丢啦<br/>
        <p style="font-size: 16px">
            原因:<font color="red" size="20px"><span name="message" th:text="${message}"/></font><br/>
            地址:<a th:href="${url}" rel="external nofollow" ><span name="url" th:text="${url}"/></a><br/>
        </p>
    </div>
    <div class="hr"></div>
    <div class="context">
        <p>您可以返回上一页重试,或直接向我们反馈错误报告
            <br/>
            联系地址:<a href=" rel="external nofollow"  >String_day</a><br/>
            联系电话:<span>18828886888</span>
        </p>
    </div>
</body>
</html>
访问错误查看跳转页面
到此这篇关于SpringBoot配置GlobalExceptionHandler全局异常处理器案例的文章就介绍到这了,更多相关SpringBoot配置GlobalExceptionHandler内容请搜索无名以前的文章或继续浏览下面的相关文章希望大家以后多多支持无名!

浅谈java如何实现Redis的LRU缓存机制
Java异步非阻塞编程的几种方式总结

同类资源