溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

SpringBoot異常處理的原理是什么

發(fā)布時間:2021-06-21 18:07:34 來源:億速云 閱讀:158 作者:Leah 欄目:開發(fā)技術(shù)

SpringBoot異常處理的原理是什么,相信很多沒有經(jīng)驗的人對此束手無策,為此本文總結(jié)了問題出現(xiàn)的原因和解決方法,通過這篇文章希望你能解決這個問題。

異常處理流程

執(zhí)行目標(biāo)方法,目標(biāo)方法運行期間有任何異常都會被catch捕獲,并標(biāo)志當(dāng)前請求結(jié)束,dispatchException拋出異常

SpringBoot異常處理的原理是什么

進入視圖解析流程,并渲染頁面,發(fā)生異常時,參數(shù)mv為空,傳入捕獲的異常dispatchException

SpringBoot異常處理的原理是什么

處理handler發(fā)生的異常,處理完成返回ModelAndView

SpringBoot異常處理的原理是什么

(1)遍歷所有的HandlerExceptionResolvers,找到可以處理當(dāng)前異常的解析器來解析異常

SpringBoot異常處理的原理是什么

(2)調(diào)用resolveException解析異常,傳入requestresponse對象,哪個方法,發(fā)生的異常,然后自定義異常處理返回ModelAndView

SpringBoot異常處理的原理是什么

(3)系統(tǒng)默認的異常解析器

SpringBoot異常處理的原理是什么

DefaultErrorAttributes先來處理異常,把異常信息保存到request域并返回null

SpringBoot異常處理的原理是什么

ExceptionHandlerExceptionResolver用來處理標(biāo)注了@ExceptionHandler注解的方法異常

ResponseStatusExceptionResolver用來處理標(biāo)注了@ResponseStatus注解的方法異常

DefaultHandlerExceptionResolver默認的處理器異常解析器,處理一些常見的異常

(4)如果沒有任何解析器能夠處理異常,異常就會拋出

SpringBoot異常處理的原理是什么

(5)如果沒有任何解析器能夠處理當(dāng)前異常,最終就會發(fā)送/error請求,將保存的異常信息轉(zhuǎn)發(fā)到/error。BasicErrorController專門來處理/error請求,BasicErrorController會遍歷所有的ErrorViewResolver解析錯誤視圖,如果沒有自定義的錯誤視圖解析器,就會使用默認的DefaultErrorViewResolver,會把響應(yīng)碼作為錯誤頁的地址,模板引擎最終響應(yīng)這個頁面。

幾種異常處理方式及原理

1.自定義錯誤頁,error/404.html、error/5xx.html。有精確的錯誤狀態(tài)碼頁面就匹配精確,沒有就找 4xx.html,如果都沒有就觸發(fā)白頁

2.使用@ControllerAdvice@ExceptionHandler處理全局異常,底層是ExceptionHandlerExceptionResolver 支持的

SpringBoot異常處理的原理是什么

3.使用@ResponseStatus和自定義異常。底層是 ResponseStatusExceptionResolver ,底層調(diào)用 response.sendError(statusCode, resolvedReason),Tomcat會收到一個error。請求最后new一個空的ModelAndView返回,這樣任何處理解析器都處理不了當(dāng)前的異常,最終就會發(fā)送/error請求,BasicErrorController專門來處理/error請求,適配4xx.html或者5xx.html頁面

SpringBoot異常處理的原理是什么
SpringBoot異常處理的原理是什么
SpringBoot異常處理的原理是什么

4.Spring底層的異常,如參數(shù)類型轉(zhuǎn)換異常。底層是DefaultHandlerExceptionResolver 處理框架底層的異常,底層也是response.sendError(HttpServletResponse.SC_NOT_ACCEPTABLE),Tomcat會收到一個error。請求最后new一個空的ModelAndView返回,這樣任何處理解析器都處理不了當(dāng)前的異常,最終就會發(fā)送/error請求,BasicErrorController專門來處理/error請求,適配4xx.html或者5xx.html頁面

protected ModelAndView doResolveException(
			HttpServletRequest request, HttpServletResponse response, @Nullable Object handler, Exception ex) {

		try {
			if (ex instanceof HttpRequestMethodNotSupportedException) {
				return handleHttpRequestMethodNotSupported(
						(HttpRequestMethodNotSupportedException) ex, request, response, handler);
			}
			else if (ex instanceof HttpMediaTypeNotSupportedException) {
				return handleHttpMediaTypeNotSupported(
						(HttpMediaTypeNotSupportedException) ex, request, response, handler);
			}
			else if (ex instanceof HttpMediaTypeNotAcceptableException) {
				return handleHttpMediaTypeNotAcceptable(
						(HttpMediaTypeNotAcceptableException) ex, request, response, handler);
			}
			else if (ex instanceof MissingPathVariableException) {
				return handleMissingPathVariable(
						(MissingPathVariableException) ex, request, response, handler);
			}
			else if (ex instanceof MissingServletRequestParameterException) {
				return handleMissingServletRequestParameter(
						(MissingServletRequestParameterException) ex, request, response, handler);
			}
			else if (ex instanceof ServletRequestBindingException) {
				return handleServletRequestBindingException(
						(ServletRequestBindingException) ex, request, response, handler);
			}
			else if (ex instanceof ConversionNotSupportedException) {
				return handleConversionNotSupported(
						(ConversionNotSupportedException) ex, request, response, handler);
			}
			else if (ex instanceof TypeMismatchException) {
				return handleTypeMismatch(
						(TypeMismatchException) ex, request, response, handler);
			}
			else if (ex instanceof HttpMessageNotReadableException) {
				return handleHttpMessageNotReadable(
						(HttpMessageNotReadableException) ex, request, response, handler);
			}
			else if (ex instanceof HttpMessageNotWritableException) {
				return handleHttpMessageNotWritable(
						(HttpMessageNotWritableException) ex, request, response, handler);
			}
			else if (ex instanceof MethodArgumentNotValidException) {
				return handleMethodArgumentNotValidException(
						(MethodArgumentNotValidException) ex, request, response, handler);
			}
			else if (ex instanceof MissingServletRequestPartException) {
				return handleMissingServletRequestPartException(
						(MissingServletRequestPartException) ex, request, response, handler);
			}
			else if (ex instanceof BindException) {
				return handleBindException((BindException) ex, request, response, handler);
			}
			else if (ex instanceof NoHandlerFoundException) {
				return handleNoHandlerFoundException(
						(NoHandlerFoundException) ex, request, response, handler);
			}
			else if (ex instanceof AsyncRequestTimeoutException) {
				return handleAsyncRequestTimeoutException(
						(AsyncRequestTimeoutException) ex, request, response, handler);
			}
		}
		catch (Exception handlerEx) {
			if (logger.isWarnEnabled()) {
				logger.warn("Failure while trying to resolve exception [" + ex.getClass().getName() + "]", handlerEx);
			}
		}
		return null;
	}

5.自定義實現(xiàn) HandlerExceptionResolver 處理異常,可以作為默認的全局異常處理規(guī)則

@Order(value = Ordered.HIGHEST_PRECEDENCE)
@Component
public class CustomerHandlerExceptionResolver implements HandlerExceptionResolver {
    @Override
    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {

        try {
            response.sendError(521,"I love you !");
        } catch (IOException e) {
            e.printStackTrace();
        }
        return new ModelAndView();
    }
}

SpringBoot異常處理的原理是什么

ErrorViewResolver 實現(xiàn)自定義處理異常。

(1)底層調(diào)用response.sendError時 ,error請求就會默認轉(zhuǎn)給basicErrorController,BasicErrorController專門來處理/error請求,適配4xx.html或者5xx.html頁面

(2)如果異常沒有任何解析器能處理,tomcat底層 也會調(diào)用response.sendErrorerror請求就會默認轉(zhuǎn)給basicErrorController,BasicErrorController專門來處理/error請求,適配4xx.html或者5xx.html頁面。

(3)basicErrorController 要去的頁面地址是由 ErrorViewResolver這個錯誤視圖解析器決定的,即適配4xx.html或者5xx.html頁面。

看完上述內(nèi)容,你們掌握SpringBoot異常處理的原理是什么的方法了嗎?如果還想學(xué)到更多技能或想了解更多相關(guān)內(nèi)容,歡迎關(guān)注億速云行業(yè)資訊頻道,感謝各位的閱讀!

向AI問一下細節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI