SpringBoot 全局异常处理器

SpringBoot 全局异常处理器

使用 SpringBoot 开发项目时,在每个接口使用 try{}catch{} 捕捉异常是很麻烦的事,可以通过创建全局异常处理器统一解决异常。

1、定义全局异常处理器

@ControllerAdvice 用于声明一个类为全局异常处理器,@ExceptionHandler注解一个方法为异常处理方法。

//该注解定义全局异常处理器
@ControllerAdvice
public class GlobalExceptionHandler {

    Logger logger = LoggerFactory.getLogger(getClass());

    //该注解声明方法为异常处理方法,value可指定哪种异常访问该方法
    @ExceptionHandler(value = Exception.class)
    public ModelAndView exception(HttpServletRequest request, Exception e){
        logger.info("==========抛出异常==========");
        ModelAndView view = new ModelAndView();
        view.addObject("status", "500");
        view.addObject("url", request.getRequestURI());
        if (e instanceof ArithmeticException){
            view.addObject("exception", "算术运算异常");
        } else if (e instanceof NullPointerException) {
            view.addObject("exception", "对象空指针");
        } else if ( e instanceof ArrayIndexOutOfBoundsException) {
            view.addObject("exception", "数组越界");
        } else {
            view.addObject("exception", e.toString());
        }
        //设置访问的视图
        view.setViewName("error");
        return view;
    }
}

2、测试

本测试采用 thymeleaf 进行测试, 引入依赖

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
    <version>2.5.0</version>
</dependency>

设计发生异常的页面 error.html

<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml"
      xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
error错误页面
<p th:text="'状态码:' + ${status}"></p>
<p th:text="'请求路径:' + ${url}"></p>
<p th:text="'异常:' + ${exception}"></p>
</body>
</html>

添加测试接口

@GetMapping(value = "/findById")
@ResponseBody
public Result findById(Long id) {
    //将抛出数组越界异常
    int i = id/0;
    User user = userService.findById(id);
    return ResultUtil.success(user);
}

访问接口,将抛出异常并跳转到 error.html

image-20210529151422368

自我控制是最强者的本能-萧伯纳
原文地址:https://www.cnblogs.com/CF1314/p/14825431.html