Springboot實(shí)現(xiàn)全局自定義異常的方法詳解
前言
SpringBoot的項(xiàng)目已經(jīng)對(duì)有一定的異常處理了,但是對(duì)于我們開(kāi)發(fā)者而言可能就不太合適了,因此我們需要對(duì)這些異常進(jìn)行統(tǒng)一的捕獲并處理。SpringBoot中有一個(gè)ControllerAdvice的注解,使用該注解表示開(kāi)啟了全局異常的捕獲,我們只需在自定義一個(gè)方法使用ExceptionHandler注解然后定義捕獲異常的類(lèi)型即可對(duì)這些捕獲的異常進(jìn)行統(tǒng)一的處理。
自定義基礎(chǔ)接口類(lèi)
定義一個(gè)基礎(chǔ)的接口類(lèi),自定義的錯(cuò)誤描述枚舉類(lèi)需實(shí)現(xiàn)該接口。
代碼如下:
public interface BaseErrorInfoInterface { /** 錯(cuò)誤碼 */ String getCode(); /** 錯(cuò)誤描述*/ String getMsg(); }
自定義枚舉類(lèi)
然后自定義一個(gè)枚舉類(lèi),并實(shí)現(xiàn)該接口。
代碼如下:
import lombok.Getter; @Getter public enum ErrorCodeAndMsg implements BaseErrorInfoInterface{ SUCCESS("200", "成功!"), BODY_NOT_MATCH("400","請(qǐng)求的數(shù)據(jù)格式不符!"), SIGNATURE_NOT_MATCH("401","請(qǐng)求的數(shù)字簽名不匹配!"), NOT_FOUND("404", "未找到該資源!"), INTERNAL_SERVER_ERROR("500", "服務(wù)器內(nèi)部錯(cuò)誤!"), SERVER_BUSY("503","服務(wù)器正忙,請(qǐng)稍后再試!"), STUDENG_NULL("0003", "學(xué)號(hào)不能為空"); private String code; private String msg; ErrorCodeAndMsg(String code, String msg) { this.code = code; this.msg = msg; } public String getCode() { return code; } public String getMsg() { return msg; } }
自定義異常類(lèi)
定義一個(gè)異常類(lèi),用于處理我們發(fā)生的業(yè)務(wù)異常。
代碼如下:
import lombok.Getter; /** * 統(tǒng)一異常捕獲類(lèi) * Created by Tiger on 2018/10/9. */ @Getter public class StudentException extends RuntimeException{ private String code; private String msg; public StudentException() { super(); } public StudentException(BaseErrorInfoInterface errorInfoInterface) { super(errorInfoInterface.getCode()); this.code = errorInfoInterface.getCode(); this.msg = errorInfoInterface.getMsg(); } public StudentException(BaseErrorInfoInterface errorInfoInterface, Throwable cause) { super(errorInfoInterface.getCode(), cause); this.code = errorInfoInterface.getCode(); this.msg = errorInfoInterface.getMsg(); } public StudentException(String errorMsg) { super(errorMsg); this.msg = errorMsg; } public StudentException(String errorCode, String errorMsg) { super(errorCode); this.code = errorCode; this.msg = errorMsg; } public StudentException(String errorCode, String errorMsg, Throwable cause) { super(errorCode, cause); this.code = errorCode; this.msg = errorMsg; } public String getErrorCode() { return code; } public void setErrorCode(String errorCode) { this.code = errorCode; } public String getErrorMsg() { return msg; } public void setErrorMsg(String errorMsg) { this.msg = errorMsg; } public String getMessage() { return msg; } @Override public Throwable fillInStackTrace() { return this; } }
自定義數(shù)據(jù)格式
順便這里定義一下數(shù)據(jù)的傳輸格式。
代碼如下:
public class ResultBody { /** * 響應(yīng)代碼 */ private String code; /** * 響應(yīng)消息 */ private String message; /** * 響應(yīng)結(jié)果 */ private Object result; public ResultBody() { } public String getCode() { return code; } public void setCode(String code) { this.code = code; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } public Object getResult() { return result; } public void setResult(Object result) { this.result = result; } /** * 成功 * * @return */ public static ResultBody success() { return success(null); } /** * 成功 * @param data * @return */ public static ResultBody success(Object data) { ResultBody rb = new ResultBody(); rb.setCode(ErrorCodeAndMsg.SUCCESS.getCode()); rb.setMessage(ErrorCodeAndMsg.SUCCESS.getMsg()); rb.setResult(data); return rb; } /** * 失敗 */ public static ResultBody error(BaseErrorInfoInterface errorInfo) { ResultBody rb = new ResultBody(); rb.setCode(errorInfo.getCode()); rb.setMessage(errorInfo.getMsg()); rb.setResult(null); return rb; } /** * 失敗 */ public static ResultBody error(String code, String message) { ResultBody rb = new ResultBody(); rb.setCode(code); rb.setMessage(message); rb.setResult(null); return rb; } /** * 失敗 */ public static ResultBody error( String message) { ResultBody rb = new ResultBody(); rb.setCode("-1"); rb.setMessage(message); rb.setResult(null); return rb; } /*@Override public String toString() { return JSONObject.toJSONString(this); }*/ }
自定義全局異常處理類(lèi)
最后我們?cè)趤?lái)編寫(xiě)一個(gè)自定義全局異常處理的類(lèi)。
代碼如下:
@ControllerAdvice public class GlobalExceptionHandler { private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class); /** * 處理自定義的業(yè)務(wù)異常 * @param req * @param e * @return */ @ExceptionHandler(value = BizException.class) @ResponseBody public ResultBody bizExceptionHandler(HttpServletRequest req, BizException e){ logger.error("發(fā)生業(yè)務(wù)異常!原因是:{}",e.getErrorMsg()); return ResultBody.error(e.getErrorCode(),e.getErrorMsg()); } /** * 處理空指針的異常 * @param req * @param e * @return */ @ExceptionHandler(value =NullPointerException.class) @ResponseBody public ResultBody exceptionHandler(HttpServletRequest req, NullPointerException e){ logger.error("發(fā)生空指針異常!原因是:",e); return ResultBody.error(CommonEnum.BODY_NOT_MATCH); } /** * 處理其他異常 * @param req * @param e * @return */ @ExceptionHandler(value =Exception.class) @ResponseBody public ResultBody exceptionHandler(HttpServletRequest req, Exception e){ logger.error("未知異常!原因是:",e); return ResultBody.error(CommonEnum.INTERNAL_SERVER_ERROR); } }
到此這篇關(guān)于Springboot實(shí)現(xiàn)全局自定義異常的方法詳解的文章就介紹到這了,更多相關(guān)Springboot全局自定義異常內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Java空指針異常處理之判空、Optional與Assert解析
本文將深入探討三種處理空指針異常的方法:傳統(tǒng)的判空檢查、Java 8引入的Optional類(lèi)以及使用斷言(Assert),通過(guò)代碼示例和應(yīng)用場(chǎng)景分析,幫助開(kāi)發(fā)者理解并選擇最適合的方案以提升程序健壯性,感興趣的朋友一起看看吧2025-01-01Spring Boot 中的任務(wù)執(zhí)行器基本概念及使用方法
務(wù)執(zhí)行器是 Spring Boot 中的一個(gè)非常實(shí)用的模塊,它可以簡(jiǎn)化異步任務(wù)的開(kāi)發(fā)和管理,在本文中,我們介紹了任務(wù)執(zhí)行器的基本概念和使用方法,以及一個(gè)完整的示例代碼,需要的朋友可以參考下2023-07-07java 中HashMap、HashSet、TreeMap、TreeSet判斷元素相同的幾種方法比較
這篇文章主要介紹了從源碼的角度淺析HashMap、TreeMap元素的存儲(chǔ)和獲取元素的邏輯;從Map與Set之間的關(guān)系淺析常用的Set中元素的存儲(chǔ)和判斷是否重復(fù)的邏輯,需要的朋友可以參考下2017-01-01logback-spring.xml的內(nèi)容格式詳解
這篇文章主要介紹了logback-spring.xml的內(nèi)容格式詳解,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的的朋友參考下吧2023-11-11SpringMVC返回的ResponseEntity出現(xiàn)亂碼及解決
這篇文章主要介紹了SpringMVC返回的ResponseEntity出現(xiàn)亂碼及解決方案,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-02-02解析Java的可變長(zhǎng)參數(shù)列表及其使用時(shí)的注意點(diǎn)
這篇文章主要介紹了解析Java的可變參數(shù)列表及其使用時(shí)的注意點(diǎn),注意可變參數(shù)必須位于最后一項(xiàng),需要的朋友可以參考下2016-03-03剖析Spring WebFlux反應(yīng)式編程設(shè)計(jì)及工作原理
這篇文章主要為大家介紹了Spring WebFlux反應(yīng)式編程模型工作原理的剖析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步早日升職加薪2022-02-02Springboot Thymeleaf數(shù)字對(duì)象使用方法
這篇文章主要介紹了Springboot Thymeleaf數(shù)字對(duì)象使用方法,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2007-09-09