Springboot實現(xiàn)全局自定義異常的方法詳解
前言
SpringBoot的項目已經對有一定的異常處理了,但是對于我們開發(fā)者而言可能就不太合適了,因此我們需要對這些異常進行統(tǒng)一的捕獲并處理。SpringBoot中有一個ControllerAdvice的注解,使用該注解表示開啟了全局異常的捕獲,我們只需在自定義一個方法使用ExceptionHandler注解然后定義捕獲異常的類型即可對這些捕獲的異常進行統(tǒng)一的處理。
自定義基礎接口類
定義一個基礎的接口類,自定義的錯誤描述枚舉類需實現(xiàn)該接口。
代碼如下:
public interface BaseErrorInfoInterface { /** 錯誤碼 */ String getCode(); /** 錯誤描述*/ String getMsg(); }
自定義枚舉類
然后自定義一個枚舉類,并實現(xiàn)該接口。
代碼如下:
import lombok.Getter; @Getter public enum ErrorCodeAndMsg implements BaseErrorInfoInterface{ SUCCESS("200", "成功!"), BODY_NOT_MATCH("400","請求的數據格式不符!"), SIGNATURE_NOT_MATCH("401","請求的數字簽名不匹配!"), NOT_FOUND("404", "未找到該資源!"), INTERNAL_SERVER_ERROR("500", "服務器內部錯誤!"), SERVER_BUSY("503","服務器正忙,請稍后再試!"), STUDENG_NULL("0003", "學號不能為空"); 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; } }
自定義異常類
定義一個異常類,用于處理我們發(fā)生的業(yè)務異常。
代碼如下:
import lombok.Getter; /** * 統(tǒng)一異常捕獲類 * 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; } }
自定義數據格式
順便這里定義一下數據的傳輸格式。
代碼如下:
public class ResultBody { /** * 響應代碼 */ private String code; /** * 響應消息 */ private String message; /** * 響應結果 */ 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); }*/ }
自定義全局異常處理類
最后我們在來編寫一個自定義全局異常處理的類。
代碼如下:
@ControllerAdvice public class GlobalExceptionHandler { private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class); /** * 處理自定義的業(yè)務異常 * @param req * @param e * @return */ @ExceptionHandler(value = BizException.class) @ResponseBody public ResultBody bizExceptionHandler(HttpServletRequest req, BizException e){ logger.error("發(fā)生業(yè)務異常!原因是:{}",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); } }
到此這篇關于Springboot實現(xiàn)全局自定義異常的方法詳解的文章就介紹到這了,更多相關Springboot全局自定義異常內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Java空指針異常處理之判空、Optional與Assert解析
本文將深入探討三種處理空指針異常的方法:傳統(tǒng)的判空檢查、Java 8引入的Optional類以及使用斷言(Assert),通過代碼示例和應用場景分析,幫助開發(fā)者理解并選擇最適合的方案以提升程序健壯性,感興趣的朋友一起看看吧2025-01-01Spring Boot 中的任務執(zhí)行器基本概念及使用方法
務執(zhí)行器是 Spring Boot 中的一個非常實用的模塊,它可以簡化異步任務的開發(fā)和管理,在本文中,我們介紹了任務執(zhí)行器的基本概念和使用方法,以及一個完整的示例代碼,需要的朋友可以參考下2023-07-07java 中HashMap、HashSet、TreeMap、TreeSet判斷元素相同的幾種方法比較
這篇文章主要介紹了從源碼的角度淺析HashMap、TreeMap元素的存儲和獲取元素的邏輯;從Map與Set之間的關系淺析常用的Set中元素的存儲和判斷是否重復的邏輯,需要的朋友可以參考下2017-01-01SpringMVC返回的ResponseEntity出現(xiàn)亂碼及解決
這篇文章主要介紹了SpringMVC返回的ResponseEntity出現(xiàn)亂碼及解決方案,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-02-02