SpringBoot中的統(tǒng)一異常處理詳細(xì)解析
一、概述
1、統(tǒng)一異常處理介紹
Spring在3.2版本增加了一個(gè)注解@ControllerAdvice,可以與@ExceptionHandler、@InitBinder、@ModelAttribute 等注解注解配套使用。不過(guò)跟異常處理相關(guān)的只有注解@ExceptionHandler,從字面上看,就是 異常處理器 的意思
2、原理和目標(biāo)
簡(jiǎn)單的說(shuō),該注解可以把異常處理器應(yīng)用到所有控制器,而不是單個(gè)控制器。借助該注解,我們可以實(shí)現(xiàn):在獨(dú)立的某個(gè)地方,比如單獨(dú)一個(gè)類(lèi),定義一套對(duì)各種異常的處理機(jī)制,然后在類(lèi)的簽名加上注解@ControllerAdvice,統(tǒng)一對(duì) 不同階段的、不同異常 進(jìn)行處理。這就是統(tǒng)一異常處理的原理。
對(duì)異常按階段進(jìn)行分類(lèi),大體可以分成:進(jìn)入Controller前的異常 和 Service 層異常
目標(biāo)就是消滅95%以上的 try catch 代碼塊,并以?xún)?yōu)雅的 Assert(斷言) 方式來(lái)校驗(yàn)業(yè)務(wù)的異常情況,只關(guān)注業(yè)務(wù)邏輯,而不用花費(fèi)大量精力寫(xiě)冗余的 try catch 代碼塊。
二、Assert(斷言)
1、概述
**Assert(斷言)**是Spring 家族的 org.springframework.util.Assert,在我們寫(xiě)測(cè)試用例的時(shí)候經(jīng)常會(huì)用到,使用斷言能讓我們編碼的時(shí)候有一種非一般絲滑的感覺(jué)
Assert 的部分源碼,可以看到,Assert 其實(shí)就是幫我們把 if {…} 封裝了一下,拋出的異常是IllegalArgumentException()
public abstract class Assert { public Assert() { } public static void notNull(@Nullable Object object, String message) { if (object == null) { throw new IllegalArgumentException(message); } } }
2、Assert自定義實(shí)戰(zhàn)
2.1 自定義接口Assert
Assert斷言方法是使用接口的默認(rèn)方法定義的,然后有沒(méi)有發(fā)現(xiàn)當(dāng)斷言失敗后,拋出的異常不是具體的某個(gè)異常,而是交由2個(gè)newException接口方法提供。因?yàn)闃I(yè)務(wù)邏輯中出現(xiàn)的異?;径际菍?duì)應(yīng)特定的場(chǎng)景,比如根據(jù)用戶(hù)id獲取用戶(hù)信息,查詢(xún)結(jié)果為null,此時(shí)拋出的異??赡転閁serNotFoundException,并且有特定的異常碼(比如7001)和異常信息"用戶(hù)不存在"。所以具體拋出什么異常,有Assert的實(shí)現(xiàn)類(lèi)決定。
public interface Assert { /** * 創(chuàng)建異常 * @param args * @return */ BaseException newException(Object... args); /** * 創(chuàng)建異常 * @param t * @param args * @return */ BaseException newException(Throwable t, Object... args); /** * <p>斷言對(duì)象<code>obj</code>非空。如果對(duì)象<code>obj</code>為空,則拋出異常 * * @param obj 待判斷對(duì)象 */ default void assertNotNull(Object obj) { if (obj == null) { throw newException(obj); } } /** * <p>斷言對(duì)象<code>obj</code>非空。如果對(duì)象<code>obj</code>為空,則拋出異常 * <p>異常信息<code>message</code>支持傳遞參數(shù)方式,避免在判斷之前進(jìn)行字符串拼接操作 * * @param obj 待判斷對(duì)象 * @param args message占位符對(duì)應(yīng)的參數(shù)列表 */ default void assertNotNull(Object obj, Object... args) { if (obj == null) { throw newException(args); } } }
2.2 自定義異常
public interface IResponseEnum { int getCode(); String getMessage(); } /** * <p>業(yè)務(wù)異常</p> * <p>業(yè)務(wù)處理時(shí),出現(xiàn)異常,可以?huà)伋鲈摦惓?lt;/p> */ public class BusinessException extends BaseException { private static final long serialVersionUID = 1L; public BusinessException(IResponseEnum responseEnum, Object[] args, String message) { super(responseEnum, args, message); } public BusinessException(IResponseEnum responseEnum, Object[] args, String message, Throwable cause) { super(responseEnum, args, message, cause); } }
2.3 Enum整合
代碼示例中定義了兩個(gè)枚舉實(shí)例:BAD_LICENCE_TYPE、LICENCE_NOT_FOUND,分別對(duì)應(yīng)了BadLicenceTypeException、LicenceNotFoundException兩種異常。
以后每增加一種異常情況,只需增加一個(gè)枚舉實(shí)例即可,再也不用每一種異常都定義一個(gè)異常類(lèi)了
public interface BusinessExceptionAssert extends IResponseEnum, Assert { @Override default BaseException newException(Object... args) { String msg = MessageFormat.format(this.getMessage(), args); return new BusinessException(this, args, msg); } @Override default BaseException newException(Throwable t, Object... args) { String msg = MessageFormat.format(this.getMessage(), args); return new BusinessException(this, args, msg, t); } } @Getter @AllArgsConstructor public enum ResponseEnum implements BusinessExceptionAssert { /** * Bad licence type */ BAD_LICENCE_TYPE(7001, "Bad licence type."), /** * Licence not found */ LICENCE_NOT_FOUND(7002, "Licence not found.") ; /** * 返回碼 */ private int code; /** * 返回消息 */ private String message; }
2.4 實(shí)戰(zhàn)檢測(cè)
使用枚舉類(lèi)結(jié)合(繼承)Assert,只需根據(jù)特定的異常情況定義不同的枚舉實(shí)例,如上面的BAD_LICENCE_TYPE、LICENCE_NOT_FOUND,就能夠針對(duì)不同情況拋出特定的異常(這里指攜帶特定的異常碼和異常消息),這樣既不用定義大量的異常類(lèi),同時(shí)還具備了斷言的良好可讀性
private void checkNotNull(Licence licence) { ResponseEnum.LICENCE_NOT_FOUND.assertNotNull(licence,"測(cè)試"); } // 替代下面的方法 private void checkNotNull(Licence licence) { if (licence == null) { throw new LicenceNotFoundException(); // 或者這樣 throw new BusinessException(7001, "Bad licence type."); } }
三、統(tǒng)一異常處理器
1、異常處理器說(shuō)明
1.1 handleServletException
一個(gè)http請(qǐng)求,在到達(dá)Controller前,會(huì)對(duì)該請(qǐng)求的請(qǐng)求信息與目標(biāo)控制器信息做一系列校驗(yàn)
- NoHandlerFoundException:首先根據(jù)請(qǐng)求Url查找有沒(méi)有對(duì)應(yīng)的控制器,若沒(méi)有則會(huì)拋該異常,也就是大家非常熟悉的404異常,但是實(shí)際上當(dāng)出現(xiàn)404的時(shí)候,默認(rèn)是不拋異常的,而是 forward跳轉(zhuǎn)到/error控制器,spring也提供了默認(rèn)的error控制器,如果要拋出異常,需要配置
spring.mvc.throw-exception-if-no-handler-found=true spring.web.resources.add-mappings=false
- HttpRequestMethodNotSupportedException:若匹配到了(匹配結(jié)果是一個(gè)列表,不同的是http方法不同,如:Get、Post等),則嘗試將請(qǐng)求的http方法與列表的控制器做匹配,若沒(méi)有對(duì)應(yīng)http方法的控制器,則拋該異常;
- HttpMediaTypeNotSupportedException:然后再對(duì)請(qǐng)求頭與控制器支持的做比較,比如content-type請(qǐng)求頭,若控制器的參數(shù)簽名包含注解@RequestBody,但是請(qǐng)求的content-type請(qǐng)求頭的值沒(méi)有包含application/json,那么會(huì)拋該異常(當(dāng)然,不止這種情況會(huì)拋這個(gè)異常);
- MissingPathVariableException:未檢測(cè)到路徑參數(shù)。比如url為:/licence/{licenceId},參數(shù)簽名包含@PathVariable("licenceId"),當(dāng)請(qǐng)求的url為/licence,在沒(méi)有明確定義url為/licence的情況下,會(huì)被判定為:缺少路徑參數(shù);
- MissingServletRequestParameterException:缺少請(qǐng)求參數(shù)。比如定義了參數(shù)@RequestParam("licenceId") String licenceId,但發(fā)起請(qǐng)求時(shí),未攜帶該參數(shù),則會(huì)拋該異常;
- TypeMismatchException: 參數(shù)類(lèi)型匹配失敗。比如:接收參數(shù)為L(zhǎng)ong型,但傳入的值確是一個(gè)字符串,那么將會(huì)出現(xiàn)類(lèi)型轉(zhuǎn)換失敗的情況,這時(shí)會(huì)拋該異常;
- HttpMessageNotReadableException:與上面的HttpMediaTypeNotSupportedException舉的例子完全相反,即請(qǐng)求頭攜帶了"content-type: application/json;charset=UTF-8",但接收參數(shù)卻沒(méi)有添加注解@RequestBody,或者請(qǐng)求體攜帶的 json 串反序列化成 pojo 的過(guò)程中失敗了,也會(huì)拋該異常;
- HttpMessageNotWritableException:返回的 pojo 在序列化成 json 過(guò)程失敗了,那么拋該異常;
1.2 handleBindException和handleValidException
參數(shù)校驗(yàn)異常
1.3 handleBusinessException、handleBaseException
處理自定義的業(yè)務(wù)異常,只是handleBaseException處理的是除了 BusinessException 意外的所有業(yè)務(wù)異常。就目前來(lái)看,這2個(gè)是可以合并成一個(gè)的
1.4 handleException
處理所有未知的異常,比如操作數(shù)據(jù)庫(kù)失敗的異常。
注:上面的handleServletException、handleException 這兩個(gè)處理器,返回的異常信息,不同環(huán)境返回的可能不一樣,以為這些異常信息都是框架自帶的異常信息,一般都是英文的,不太好直接展示給用戶(hù)看,所以統(tǒng)一返回SERVER_ERROR代表的異常信息
2、自定義統(tǒng)一異常處理器類(lèi)
將異常分成幾類(lèi),實(shí)際上只有兩大類(lèi),一類(lèi)是ServletException、ServiceException,還記得上文提到的 按階段分類(lèi) 嗎,即對(duì)應(yīng) 進(jìn)入Controller前的異常 和 Service 層異常;然后 ServiceException 再分成自定義異常、未知異常。對(duì)應(yīng)關(guān)系如下:
- 進(jìn)入Controller前的異常: handleServletException、handleBindException、handleValidException
- 自定義異常:handleBusinessException、handleBaseException
- 未知異常: handleException
@Slf4j @Component @ControllerAdvice @ConditionalOnWebApplication @ConditionalOnMissingBean(UnifiedExceptionHandler.class) public class UnifiedExceptionHandler { /** * 生產(chǎn)環(huán)境 */ private final static String ENV_PROD = "prod"; @Autowired private UnifiedMessageSource unifiedMessageSource; /** * 當(dāng)前環(huán)境 */ @Value("${spring.profiles.active}") private String profile; /** * 獲取國(guó)際化消息 * 這里可以做處理 * @param e 異常 * @return */ public String getMessage(BaseException e) { String code = "response." + e.getResponseEnum().toString(); String message = unifiedMessageSource.getMessage(code, e.getArgs()); if (message == null || message.isEmpty()) { return e.getMessage(); } return message; } /** * 業(yè)務(wù)異常 * * @param e 異常 * @return 異常結(jié)果 */ @ExceptionHandler(value = BusinessException.class) @ResponseBody public ErrorResponse handleBusinessException(BaseException e) { log.error(e.getMessage(), e); return new ErrorResponse(e.getResponseEnum().getCode(), getMessage(e)); } /** * 自定義異常 * * @param e 異常 * @return 異常結(jié)果 */ @ExceptionHandler(value = BaseException.class) @ResponseBody public ErrorResponse handleBaseException(BaseException e) { log.error(e.getMessage(), e); return new ErrorResponse(e.getResponseEnum().getCode(), getMessage(e)); } /** * Controller上一層相關(guān)異常 * * @param e 異常 * @return 異常結(jié)果 */ @ExceptionHandler({ NoHandlerFoundException.class, HttpRequestMethodNotSupportedException.class, HttpMediaTypeNotSupportedException.class, MissingPathVariableException.class, MissingServletRequestParameterException.class, TypeMismatchException.class, HttpMessageNotReadableException.class, HttpMessageNotWritableException.class, // BindException.class, // MethodArgumentNotValidException.class HttpMediaTypeNotAcceptableException.class, ServletRequestBindingException.class, ConversionNotSupportedException.class, MissingServletRequestPartException.class, AsyncRequestTimeoutException.class }) @ResponseBody public ErrorResponse handleServletException(Exception e) { log.error(e.getMessage(), e); int code = CommonResponseEnum.SERVER_ERROR.getCode(); try { ServletResponseEnum servletExceptionEnum = ServletResponseEnum.valueOf(e.getClass().getSimpleName()); code = servletExceptionEnum.getCode(); } catch (IllegalArgumentException e1) { log.error("class [{}] not defined in enum {}", e.getClass().getName(), ServletResponseEnum.class.getName()); } if (ENV_PROD.equals(profile)) { // 當(dāng)為生產(chǎn)環(huán)境, 不適合把具體的異常信息展示給用戶(hù), 比如404. code = CommonResponseEnum.SERVER_ERROR.getCode(); BaseException baseException = new BaseException(CommonResponseEnum.SERVER_ERROR); String message = getMessage(baseException); return new ErrorResponse(code, message); } return new ErrorResponse(code, e.getMessage()); } /** * 參數(shù)綁定異常 * * @param e 異常 * @return 異常結(jié)果 */ @ExceptionHandler(value = BindException.class) @ResponseBody public ErrorResponse handleBindException(BindException e) { log.error("參數(shù)綁定校驗(yàn)異常", e); return wrapperBindingResult(e.getBindingResult()); } /** * 參數(shù)校驗(yàn)異常,將校驗(yàn)失敗的所有異常組合成一條錯(cuò)誤信息 * * @param e 異常 * @return 異常結(jié)果 */ @ExceptionHandler(value = MethodArgumentNotValidException.class) @ResponseBody public ErrorResponse handleValidException(MethodArgumentNotValidException e) { log.error("參數(shù)綁定校驗(yàn)異常", e); return wrapperBindingResult(e.getBindingResult()); } /** * 包裝綁定異常結(jié)果 * * @param bindingResult 綁定結(jié)果 * @return 異常結(jié)果 */ private ErrorResponse wrapperBindingResult(BindingResult bindingResult) { StringBuilder msg = new StringBuilder(); for (ObjectError error : bindingResult.getAllErrors()) { msg.append(", "); if (error instanceof FieldError) { msg.append(((FieldError) error).getField()).append(": "); } msg.append(error.getDefaultMessage() == null ? "" : error.getDefaultMessage()); } return new ErrorResponse(ArgumentResponseEnum.VALID_ERROR.getCode(), msg.substring(2)); } /** * 未定義異常 * * @param e 異常 * @return 異常結(jié)果 */ @ExceptionHandler(value = Exception.class) @ResponseBody public ErrorResponse handleException(Exception e) { log.error(e.getMessage(), e); if (ENV_PROD.equals(profile)) { // 當(dāng)為生產(chǎn)環(huán)境, 不適合把具體的異常信息展示給用戶(hù), 比如數(shù)據(jù)庫(kù)異常信息. int code = CommonResponseEnum.SERVER_ERROR.getCode(); BaseException baseException = new BaseException(CommonResponseEnum.SERVER_ERROR); String message = getMessage(baseException); return new ErrorResponse(code, message); } return new ErrorResponse(CommonResponseEnum.SERVER_ERROR.getCode(), e.getMessage()); } }
3、其他類(lèi)型統(tǒng)一處理器
@Slf4j @RestControllerAdvice public class GlobalExceptionHandler { /** * 沒(méi)有登錄 * @param request * @param response * @param e * @return */ @ExceptionHandler(NoLoginException.class) public Object noLoginExceptionHandler(HttpServletRequest request,HttpServletResponse response,Exception e) { log.error("[GlobalExceptionHandler][noLoginExceptionHandler] exception",e); JsonResult jsonResult = new JsonResult(); jsonResult.setCode(JsonResultCode.NO_LOGIN); jsonResult.setMessage("用戶(hù)登錄失效或者登錄超時(shí),請(qǐng)先登錄"); return jsonResult; } /** * 業(yè)務(wù)異常 * @param request * @param response * @param e * @return */ @ExceptionHandler(ServiceException.class) public Object businessExceptionHandler(HttpServletRequest request,HttpServletResponse response,Exception e) { log.error("[GlobalExceptionHandler][businessExceptionHandler] exception",e); JsonResult jsonResult = new JsonResult(); jsonResult.setCode(JsonResultCode.FAILURE); jsonResult.setMessage("業(yè)務(wù)異常,請(qǐng)聯(lián)系管理員"); return jsonResult; } /** * 全局異常處理 * @param request * @param response * @param e * @return */ @ExceptionHandler(Exception.class) public Object exceptionHandler(HttpServletRequest request,HttpServletResponse response,Exception e) { log.error("[GlobalExceptionHandler][exceptionHandler] exception",e); JsonResult jsonResult = new JsonResult(); jsonResult.setCode(JsonResultCode.FAILURE); jsonResult.setMessage("系統(tǒng)錯(cuò)誤,請(qǐng)聯(lián)系管理員"); return jsonResult; } }
4、統(tǒng)一返回結(jié)果
code、message 是所有返回結(jié)果中必有的字段,而當(dāng)需要返回?cái)?shù)據(jù)時(shí),則需要另一個(gè)字段 data 來(lái)表示。所以首先定義一個(gè) BaseResponse 來(lái)作為所有返回結(jié)果的基類(lèi)
然后定義一個(gè)通用返回結(jié)果類(lèi)CommonResponse,繼承 BaseResponse,而且多了字段 data;為了區(qū)分成功和失敗返回結(jié)果,于是再定義一個(gè) ErrorResponse
最后還有一種常見(jiàn)的返回結(jié)果,即返回的數(shù)據(jù)帶有分頁(yè)信息,因?yàn)檫@種接口比較常見(jiàn),所以有必要單獨(dú)定義一個(gè)返回結(jié)果類(lèi) QueryDataResponse,該類(lèi)繼承自 CommonResponse,只是把 data 字段的類(lèi)型限制為 QueryDdata,QueryDdata中定義了分頁(yè)信息相應(yīng)的字段,即totalCount、pageNo、 pageSize、records。其中比較常用的只有 CommonResponse 和 QueryDataResponse,但是名字又賊鬼死長(zhǎng),何不定義2個(gè)名字超簡(jiǎn)單的類(lèi)來(lái)替代呢?于是 R 和 QR 誕生了,以后返回結(jié)果的時(shí)候只需這樣寫(xiě):new R<>(data)、new QR<>(queryData)
因?yàn)檫@一套統(tǒng)一異常處理可以說(shuō)是通用的,所有可以設(shè)計(jì)成一個(gè) common包,以后每一個(gè)新項(xiàng)目/模塊只需引入該包即可
到此這篇關(guān)于SpringBoot中的統(tǒng)一異常處理詳細(xì)解析的文章就介紹到這了,更多相關(guān)SpringBoot統(tǒng)一異常處理內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
SharedingSphere?自定義脫敏規(guī)則介紹
這篇文章主要介紹了SharedingSphere?自定義脫敏規(guī)則,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-12-12Java實(shí)現(xiàn)布隆過(guò)濾器的方法步驟
布隆過(guò)濾器是可以用于判斷一個(gè)元素是不是在一個(gè)集合里,并且相比于其它的數(shù)據(jù)結(jié)構(gòu),布隆過(guò)濾器在空間和時(shí)間方面都有巨大的優(yōu)勢(shì)。下面這篇文章主要給大家介紹了關(guān)于Java實(shí)現(xiàn)布隆過(guò)濾器的相關(guān)資料,需要的朋友可以參考下2018-11-11使用Java增刪改查數(shù)據(jù)庫(kù)的操作方法
這篇文章主要介紹了使用Java增刪改查數(shù)據(jù)庫(kù)的操作方法,本文通過(guò)實(shí)例代碼給大家介紹的非常詳細(xì),感興趣的朋友跟隨小編一起看看吧2024-12-12idea使用war以及war exploded的區(qū)別說(shuō)明
本文詳細(xì)解析了war與warexploded兩種部署方式的差異及步驟,war方式是先打包成war包,再部署到服務(wù)器上;warexploded方式是直接把文件夾、class文件等移到Tomcat上部署,支持熱部署,開(kāi)發(fā)時(shí)常用,文章分別列出了warexploded模式和war包形式的具體操作步驟2024-10-10Spring Security 實(shí)現(xiàn)多種登錄方式(常規(guī)方式外的郵件、手機(jī)驗(yàn)證碼登錄)
本文主要介紹了Spring Security 實(shí)現(xiàn)多種登錄方式(常規(guī)方式外的郵件、手機(jī)驗(yàn)證碼登錄),文中通過(guò)示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2022-01-01springboot使用@Validated或@Valid注解校驗(yàn)參數(shù)方式
這篇文章主要介紹了springboot使用@Validated或@Valid注解校驗(yàn)參數(shù)方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-07-07