SpringBoot使用統(tǒng)一異常處理詳解
場景:針對異常處理,我們原來的做法是一般在最外層捕獲異常即可,例如在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);
}
}
這樣的話也能解決部分問題,但是無法獲取到自己指定的異常,引入全局統(tǒng)一異常處理的話將會極大的改善代碼,減少冗余代碼的產(chǎn)生。
自定義異常類:注意要繼承自RuntimeException而不是Exception,繼承自Exception的話,當拋出自定義異常時spring事務不會回滾
public class GlobalException extends RuntimeException {
private Integer code; //因為我需要將異常信息也返回給接口中,所以添加code區(qū)分
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;
}
}
自定義統(tǒng)一異常處理器:比較關鍵的兩個注解@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枚舉里面,方便統(tǒng)一維護
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;
}
}

這樣就實現(xiàn)了全局的統(tǒng)一異常處理,非常方便且優(yōu)雅,快快在你的項目中用起來吧!
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
Java C++解決在排序數(shù)組中查找數(shù)字出現(xiàn)次數(shù)問題
本文終于介紹了分別通過Java和C++實現(xiàn)統(tǒng)計一個數(shù)字在排序數(shù)組中出現(xiàn)的次數(shù)。文中詳細介紹了實現(xiàn)思路,感興趣的小伙伴可以跟隨小編學習一下2021-12-12
SpringCloud筆記(Hoxton)Netflix之Ribbon負載均衡示例代碼
這篇文章主要介紹了SpringCloud筆記HoxtonNetflix之Ribbon負載均衡,Ribbon是管理HTTP和TCP服務客戶端的負載均衡器,Ribbon具有一系列帶有名稱的客戶端(Named?Client),對SpringCloud?Ribbon負載均衡相關知識感興趣的朋友一起看看吧2022-06-06
Mybatis不支持batchInsertOrUpdate返顯id問題
這篇文章主要介紹了Mybatis不支持batchInsertOrUpdate返顯id問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-05-05

