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的話,當(dāng)拋出自定義異常時spring事務(wù)不會回滾
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)一異常處理器:比較關(guān)鍵的兩個注解@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)一維護(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;
}
}

這樣就實現(xiàn)了全局的統(tǒng)一異常處理,非常方便且優(yōu)雅,快快在你的項目中用起來吧!
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
mybatis中的mapper.xml使用循環(huán)語句
這篇文章主要介紹了mybatis中的mapper.xml使用循環(huán)語句,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-02-02
Java導(dǎo)入新項目報錯java:JDK?isn‘t?specified?for?module解決辦法
這篇文章主要給大家介紹了關(guān)于Java導(dǎo)入新項目報錯java:JDK?isn‘t?specified?for?module的解決辦法,當(dāng)您在導(dǎo)入Java項目時遇到錯誤時,可以嘗試以下面的方法來處理,需要的朋友可以參考下2024-05-05
pdf2swf+flexpapers實現(xiàn)類似百度文庫pdf在線閱讀
這篇文章主要介紹了pdf2swf+flexpapers實現(xiàn)類似百度文庫pdf在線閱讀的相關(guān)資料,需要的朋友可以參考下2014-10-10

