zoukankan      html  css  js  c++  java
  • 【springboot】全局异常处理

    转自:

      https://blog.csdn.net/cp026la/article/details/86495196

    前言:

    开发中异常的处理必不可少,常用的就是 throw 和 try catch,这样一个项目到最后会出现很多冗余的代码,使用全局异常处理避免过多冗余代码。

    全局异常处理:

    1、pom 依赖(延续上一章代码):

    <dependencies>
        <!-- Spring Boot Web 依赖 -->
        <!-- Web 依赖 - 包含了 spring-boot-starter-validation 依赖-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!-- Spring Boot Test 依赖 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <!-- spring-boot整合mybatis -->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.3.2</version>
        </dependency>
        <!-- mysql驱动 -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <!-- alibaba的druid数据库连接池 -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
            <version>1.1.0</version>
        </dependency>
        <!--lombok依赖-->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.16.18</version>
        </dependency>
        <!-- fastjson 依赖添加 -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.31</version>
        </dependency>
    </dependencies>  


    2、公共的结果类封装:
    这里简单封装,实际根据自己业务需求去封装。

    @Getter
    @Setter
    public class ApiResult {
        // 响应业务状态
        private Integer status;
        // 响应消息
        private String msg;
        // 响应中的数据
        private Object data;
        public static ApiResult build(Integer status, String msg, Object data) {
            return new ApiResult(status, msg, data);
        }
        public static ApiResult ok(Object data) {
            return new ApiResult(data);
        }
        public static ApiResult ok() {
            return new ApiResult(null);
        }
        public ApiResult() { }
        public static ApiResult build(Integer status, String msg) {
            return new ApiResult(status, msg, null);
        }
        public ApiResult(Integer status, String msg, Object data) {
            this.status = status;
            this.msg = msg;
            this.data = data;
        }
        public ApiResult(Object data) {
            this.status = 200;
            this.msg = "OK";
            this.data = data;
        }
    }
    

      

    3、添加全局异常处理类(在入口函数下的包中新建):

    /**
     * 全局异常处理 Handler
     * @ControllerAdvice  配置控制器通知
     * annotations 属性: 指定我们需要拦截的注解,一个或多个(多个加到大括号中,逗号分隔)
     */
    // @RestControllerAdvice = @ResponseBody + @ControllerAdvice
    @RestControllerAdvice(annotations = {RestController.class})
    @Slf4j
    public class GlobalExceptionHandler {
       /**
        * 默认统一异常处理方法
        * @ExceptionHandler 注解用来配置需要拦截的异常类型, 也可以是自定义异常
        */
       @ExceptionHandler(Exception.class)
       // 此处可以指定返回的状态码 和 返回 结果说明
       // @ResponseStatus(reason = "exception",value = HttpStatus.BAD_REQUEST)
       public Object runtimeExceptionHandler(Exception e) {
           // 打印异常信息到控制台
           e.printStackTrace();
           log.error("请求出现异常,异常信息为: {}", e.getMessage());
           // 使用公共的结果类封装返回结果, 这里我指定状态码为 400
           return ApiResult.build(400, e.getMessage());
       }
    }  


    4、异常测试类:

    /**
     * 异常处理测试 controller
     */
    @RestController
    @Slf4j
    public class ExceptionController {
         @RequestMapping(value = "/exception/{number}")
         public ApiResult exception(@PathVariable int number) {
            int res = 10 / number;
            log.info(">>>>>结果number为: {}", res);
            return ApiResult.ok();
        }
    }  


    5、测试:
      5.1、请求接口:http://localhost:8080/exception/1 结果正常
      5.2、请求接口:http://localhost:8080/exception/0 出现除以 0 错误,全局异常处理起作用,返回指定结果集。

  • 相关阅读:
    我的家庭保险方案推荐
    如何修改Total Commander配件文件的位置
    豆瓣统计-2015
    RESTful API接口设计规范
    正则表达式中 的$1,$2与实际应用
    查询排序:order by case when理解、在order By子句中使用case语句的理解
    架构设计:BFF和Serverless简介
    移动端1px细线解决方案总结
    SpringMVC中实体类属性is开头的字段返回JSON时自动去掉is开头的问题
    详解JS面向对象的三大特征之多态
  • 原文地址:https://www.cnblogs.com/wjqhuaxia/p/12148905.html
Copyright © 2011-2022 走看看