如何在SpringBoot項目里進行統(tǒng)一異常處理
前言:
需要了解的知識:
1、處理前
異常代碼:
/**
* 根據(jù)id獲取醫(yī)院設置
*
* @param id 查看的id編號
* @return
*/
@ApiOperation(value = "根據(jù)id獲取醫(yī)院設置")
@GetMapping("/findHospById/{id}")
public Result findHospById(@PathVariable Long id) {
// 模擬異常(因為除數(shù)不能為0)
int a = 1 / 0;
HospitalSet hospitalSet = hospitalSetService.getById(id);
return Result.ok(hospitalSet);
}Swagger2輸出結果:

2、進行系統(tǒng)異常全局處理
添加全局異常處理類:

代碼:
package com.fafa.yygh.common.exception;
import com.fafa.yygh.common.result.Result;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
/**
* 全局異常處理
*
* @author Sire
* @version 1.0
* @date 2022-02-02 21:01
*/
@ControllerAdvice
public class GlobalExceptionHandler {
/**
* 系統(tǒng)異常處理
*
* @param e
* @return
*/
@ExceptionHandler(Exception.class)
@ResponseBody
public Result error(Exception e) {
e.printStackTrace();
return Result.fail();
}
}Swagger2結果:

3、進行自定義異常處理
開發(fā)時,往往需要我們?nèi)ザx處理一些異常(這里還是那上面的那個異常來做測試)
創(chuàng)建自定義異常處理類:
package com.fafa.yygh.common.exception;
import com.fafa.yygh.common.result.ResultCodeEnum;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
/**
* 自定義全局異常類
*
* @author qy
*/
@Data
@ApiModel(value = "自定義全局異常類")
public class YyghException extends RuntimeException {
@ApiModelProperty(value = "異常狀態(tài)碼")
private Integer code;
/**
* 通過狀態(tài)碼和錯誤消息創(chuàng)建異常對象
*
* @param message
* @param code
*/
public YyghException(String message, Integer code) {
super(message);
this.code = code;
}
/**
* 接收枚舉類型對象
*
* @param resultCodeEnum
*/
public YyghException(ResultCodeEnum resultCodeEnum) {
super(resultCodeEnum.getMessage());
this.code = resultCodeEnum.getCode();
}
@Override
public String toString() {
return "YyghException{" +
"code=" + code +
", message=" + this.getMessage() +
'}';
}
}將其添加到GlobalExceptionHandler:
/**
* 自定義異常處理
*
* @param e
* @return
*/
@ExceptionHandler(YyghException.class)
@ResponseBody
public Result divError(YyghException e) {
return Result.build(e.getCode(), e.getMessage());
}
需要手動 try catch 一下:

效果
swagger和系統(tǒng)異常處理一樣
不過后臺輸出不一樣 :

到此這篇關于如何在SpringBoot項目里進行統(tǒng)一異常處理的文章就介紹到這了,更多相關SpringBoot異常處理內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
SpringBoot+JPA?分頁查詢指定列并返回指定實體方式
這篇文章主要介紹了SpringBoot+JPA?分頁查詢指定列并返回指定實體方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-12-12
使用RequestBodyAdvice實現(xiàn)對Http請求非法字符過濾
這篇文章主要介紹了使用RequestBodyAdvice實現(xiàn)對Http請求非法字符過濾的操作,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-06-06

