【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 錯誤,全局異常處理起作用,返回指定結果集。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM