這篇文章主要介紹了如何在SpringBoot中實現統一異常處理的相關知識,內容詳細易懂,操作簡單快捷,具有一定借鑒價值,相信大家閱讀完這篇如何在SpringBoot中實現統一異常處理文章都會有所收獲,下面我們一起來看看吧。
我們提供的服務有:網站設計、成都網站設計、微信公眾號開發、網站優化、網站認證、銅川ssl等。為千余家企事業單位解決了網站和推廣的問題。提供周到的售前咨詢和貼心的售后服務,是有科學管理、有技術的銅川網站制作公司
場景:針對異常處理,我們原來的做法是一般在最外層捕獲異常即可,例如在Controller中
@Controller
public class HelloController {
private static final Logger logger = LoggerFactory.getLogger(HelloController.class);
@GetMapping(value = "/hello")
@ResponseBody
public Result hello() {
try {
//TODO 具體的邏輯省略……
} catch (Exception e) {
logger.error("hello接口異常={}", e);
return ResultUtil.success(-1, "system error", null);
}
return ResultUtil.success(0, "success", null);
}
}這樣的話也能解決部分問題,但是無法獲取到自己指定的異常,引入全局統一異常處理的話將會極大的改善代碼,減少冗余代碼的產生。
自定義異常類:注意要繼承自RuntimeException而不是Exception,繼承自Exception的話,當拋出自定義異常時spring事務不會回滾
public class GlobalException extends RuntimeException {
private Integer code; //因為我需要將異常信息也返回給接口中,所以添加code區分
public GlobalException(Integer code,String message) {
super(message); //把自定義的message傳遞個異常父類
this.code = code;
}
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
}自定義統一異常處理器:比較關鍵的兩個注解@ControllerAdvice、@ExceptionHandler
@ControllerAdvice
public class ExceptionHandle {
@ResponseBody //因為我需要將拋出的異常返回給接口,所以加上此注解
@ExceptionHandler
public Result handle(Exception e) {
if (e instanceof GlobalException) {
GlobalException ge = (GlobalException) e;
return ResultUtil.success1(ge.getCode(), ge.getMessage());
}
return ResultUtil.success1(-1, "system error!");
}
}寫個測試類測試下
@GetMapping(value = "/hello1")
@ResponseBody
public Result hello(@RequestParam(value = "age", defaultValue = "50", required = false) Integer age) throws GlobalException {
if (age < 10) {
throw new GlobalException(ConstantEnum.LESS10.getCode(), ConstantEnum.LESS10.getMsg());
} else if (age > 50) {
throw new GlobalException(ConstantEnum.MORE50.getCode(), ConstantEnum.MORE50.getMsg());
} else {
return ResultUtil.success1(0, "success");
}
}把code、message封裝在了ConstantEnum枚舉里面,方便統一維護
public enum ConstantEnum {
ERROR(-1, "system error!"),
SUCCESS(100, "success"),
LESS10(101, "自定義異常信息-我小于10歲"),
MORE50(5001, "自定義異常信息-我大于50歲");
private Integer code;
private String msg;
public Integer getCode() {
return code;
}
public String getMsg() {
return msg;
}
ConstantEnum(Integer code, String msg) {
this.code = code;
this.msg = msg;
}
}
關于“如何在SpringBoot中實現統一異常處理”這篇文章的內容就介紹到這里,感謝各位的閱讀!相信大家對“如何在SpringBoot中實現統一異常處理”知識都有一定的了解,大家如果還想學習更多知識,歡迎關注創新互聯行業資訊頻道。
網站名稱:如何在SpringBoot中實現統一異常處理
分享網址:http://www.yijiale78.com/article14/pcssde.html
成都網站建設公司_創新互聯,為您提供動態網站、自適應網站、網站導航、網站收錄、企業網站制作、移動網站建設
聲明:本網站發布的內容(圖片、視頻和文字)以用戶投稿、用戶轉載內容為主,如果涉及侵權請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網站立場,如需處理請聯系客服。電話:028-86922220;郵箱:631063699@qq.com。內容未經允許不得轉載,或轉載時需注明來源: 創新互聯