SpringBoot使用統(tǒng)一異常處理詳解
場(chǎng)景:針對(duì)異常處理,我們?cè)瓉淼淖龇ㄊ且话阍谧钔鈱硬东@異常即可,例如在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)一異常處理的話將會(huì)極大的改善代碼,減少冗余代碼的產(chǎn)生。
自定義異常類:注意要繼承自RuntimeException而不是Exception,繼承自Exception的話,當(dāng)拋出自定義異常時(shí)spring事務(wù)不會(huì)回滾
public class GlobalException extends RuntimeException {
private Integer code; //因?yàn)槲倚枰獙惓P畔⒁卜祷亟o接口中,所以添加code區(qū)分
public GlobalException(Integer code,String message) {
super(message); //把自定義的message傳遞個(gè)異常父類
this.code = code;
}
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
}
自定義統(tǒng)一異常處理器:比較關(guān)鍵的兩個(gè)注解@ControllerAdvice、@ExceptionHandler
@ControllerAdvice
public class ExceptionHandle {
@ResponseBody //因?yàn)槲倚枰獙伋龅漠惓7祷亟o接口,所以加上此注解
@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!");
}
}
寫個(gè)測(cè)試類測(cè)試下
@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)一維護(hù)
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;
}
}

這樣就實(shí)現(xiàn)了全局的統(tǒng)一異常處理,非常方便且優(yōu)雅,快快在你的項(xiàng)目中用起來吧!
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Java C++解決在排序數(shù)組中查找數(shù)字出現(xiàn)次數(shù)問題
本文終于介紹了分別通過Java和C++實(shí)現(xiàn)統(tǒng)計(jì)一個(gè)數(shù)字在排序數(shù)組中出現(xiàn)的次數(shù)。文中詳細(xì)介紹了實(shí)現(xiàn)思路,感興趣的小伙伴可以跟隨小編學(xué)習(xí)一下2021-12-12
Java日常練習(xí)題,每天進(jìn)步一點(diǎn)點(diǎn)(34)
下面小編就為大家?guī)硪黄狫ava基礎(chǔ)的幾道練習(xí)題(分享)。小編覺得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧,希望可以幫到你2021-07-07
SpringCloud筆記(Hoxton)Netflix之Ribbon負(fù)載均衡示例代碼
這篇文章主要介紹了SpringCloud筆記HoxtonNetflix之Ribbon負(fù)載均衡,Ribbon是管理HTTP和TCP服務(wù)客戶端的負(fù)載均衡器,Ribbon具有一系列帶有名稱的客戶端(Named?Client),對(duì)SpringCloud?Ribbon負(fù)載均衡相關(guān)知識(shí)感興趣的朋友一起看看吧2022-06-06
Spring動(dòng)態(tài)代理實(shí)現(xiàn)日志功能詳解
這篇文章主要為大家詳細(xì)介紹了Spring動(dòng)態(tài)代理實(shí)現(xiàn)日志功能,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2021-08-08
Eclipse操作SVN時(shí)中斷鎖定,文件的解鎖方法
這篇文章主要介紹了Eclipse操作SVN時(shí)中斷鎖定,文件的解鎖方法,需要的朋友可以參考下2014-08-08
Mybatis不支持batchInsertOrUpdate返顯id問題
這篇文章主要介紹了Mybatis不支持batchInsertOrUpdate返顯id問題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-05-05
關(guān)于Java集合框架Collection接口詳解
這篇文章主要介紹了關(guān)于Java集合框架Collection接口詳解,Collection接口是Java集合框架中的基礎(chǔ)接口,定義了一些基本的集合操作,包括添加元素、刪除元素、遍歷集合等,需要的朋友可以參考下2023-05-05
java中將list用逗號(hào)隔開拼成字符串的4種方法例子
我們經(jīng)常在開發(fā)過程之中會(huì)遇到需要把返回的Id list轉(zhuǎn)換為一個(gè)使用逗號(hào)(,)分隔的字符串,下面這篇文章主要給大家介紹了關(guān)于java中將list用逗號(hào)隔開拼成字符串的4種方法例子,需要的朋友可以參考下2024-01-01

