温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

springboot全局异常处理代码实例

发布时间:2020-09-23 15:08:40 来源:脚本之家 阅读:182 作者:天际星痕 栏目:编程语言

这篇文章主要介绍了springboot全局异常处理代码实例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下

前言:

开发中异常的处理必不可少,常用的就是 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 错误,全局异常处理起作用,返回指定结果集。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持亿速云。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI