SpringBoot自定義錯(cuò)誤處理邏輯詳解
1. 自定義錯(cuò)誤頁(yè)面
將自定義錯(cuò)誤頁(yè)面放在 templates 的 error 文件夾下,SpringBoot 精確匹配錯(cuò)誤信息,使用 4xx.html 或者 5xx.html 頁(yè)面可以打印錯(cuò)誤信息
4xx —— 打印 status 及 message 信息
<h2 th:text="${status}">page not found</h2> <h3 th:text="${#message}">We Couldn't Find This Page</h3>
5xx—— 打印 message 及 trace 信息
<h3 th:text="${message}">Something went wrong.</h3> <p class="nrml-txt" th:text="${trace}">Why not try refreshing you page? Or you can <a href="#" rel="external nofollow" >contact our support</a> if the problem persists.</p>
2. @ControllerAdvice+@ExceptionHandler
自定義全局異常處理類(lèi),處理 ArithmeticException 及 NullPointerException 異常
package com.wanqing.admin.exception; import lombok.extern.slf4j.Slf4j; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; @Slf4j @ControllerAdvice // 使用此注釋 public class GlobalExceptionHandler { @ExceptionHandler({ArithmeticException.class, NullPointerException.class }) // 使用此注釋?zhuān)罄ㄌ?hào)內(nèi)為可以處理的異常信息 public String handleArithException(Exception e){ log.info("異常是:" + e); return "login"; // 返回一個(gè)視圖地址(ModelAndView) } }
原理:
使用 ExceptionHandlerExceptionResolver 異常處理器處理用 @ExceptionHandler 注釋的異常
3. 使用@ResponseStatus處理自定義異常
自定義異常類(lèi)示例代碼:
import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.ResponseStatus; @ResponseStatus(value = HttpStatus.FORBIDDEN, reason = "用戶(hù)數(shù)量太多~~") // 異??梢苑祷貭顟B(tài)碼信息 public class userToMany extends RuntimeException{ // 有參構(gòu)造器 public userToMany(String message){ super(message); } public userToMany(){ } }
原理:
ResponseStatusExceptionResolver 處理器可以處理 @ResponseStatus 注解的異常,得到 @ResponseStatus 注解的信息,調(diào)用 response.sendError(statusCode) 方法將錯(cuò)誤信息返回,并發(fā)送 /error 請(qǐng)求,交由底層處理
sendError —— 表示此次請(qǐng)求立刻結(jié)束,發(fā)出 /error 請(qǐng)求,SpringBoot 找誰(shuí)能處理,都不能處理返回默認(rèn)的錯(cuò)誤頁(yè)
protected ModelAndView applyStatusAndReason(int statusCode, @Nullable String reason, HttpServletResponse response) throws IOException { if (!StringUtils.hasLength(reason)) { response.sendError(statusCode); } else { String resolvedReason = this.messageSource != null ? this.messageSource.getMessage(reason, (Object[])null, reason, LocaleContextHolder.getLocale()) : reason; response.sendError(statusCode, resolvedReason); } return new ModelAndView(); }
4. 框架底層異常
使用 DefaultHandlerExceptionResolver 異常處理器能處理 SpringMVC 底層異常,其能處理我異常種類(lèi)如下
protected ModelAndView doResolveException(HttpServletRequest request, HttpServletResponse response, @Nullable Object handler, Exception ex) { try { if (ex instanceof HttpRequestMethodNotSupportedException) { return this.handleHttpRequestMethodNotSupported((HttpRequestMethodNotSupportedException)ex, request, response, handler); } // 此處省略............. if (ex instanceof HttpMessageNotWritableException) { return this.handleHttpMessageNotWritable((HttpMessageNotWritableException)ex, request, response, handler); } if (ex instanceof MethodArgumentNotValidException) { return this.handleMethodArgumentNotValidException((MethodArgumentNotValidException)ex, request, response, handler); } } catch (Exception var6) { if (this.logger.isWarnEnabled()) { this.logger.warn("Failure while trying to resolve exception [" + ex.getClass().getName() + "]", var6); } } return null; }
5. 自定義異常解析器
自定義異常解析器需要滿(mǎn)足以下:
- 實(shí)現(xiàn) HandlerExceptionResolver 接口并注冊(cè)到容器中(@Component)
- 在自定義解析器中實(shí)現(xiàn) resolveException 方法,方法內(nèi)可通過(guò) sendError 方法返回錯(cuò)誤信息并返回一空視圖,交給底層將錯(cuò)誤信息解析拼接為最終頁(yè)面
- 可以通過(guò) @Order 注釋調(diào)整自定義異常解析器的優(yōu)先級(jí),value越小優(yōu)先級(jí)越高
自定義異常解析器示例代碼:
import javax.servlet.http.HttpServletResponse; import java.io.IOException; @Order(value = Ordered.HIGHEST_PRECEDENCE) // 優(yōu)先級(jí)數(shù)字越小,優(yōu)先級(jí)越高 @Component // 注冊(cè)到容器中 public class CustomerHandlerResolver implements HandlerExceptionResolver { @Override public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) { try { httpServletResponse.sendError(511, "我不喜歡的錯(cuò)誤"); } catch (IOException e1){ e1.printStackTrace(); } return new ModelAndView(); } }
自定義異常處理器被加入(未調(diào)整優(yōu)先級(jí)時(shí),默認(rèn)加到最后):
6. ErrorViewResolver實(shí)現(xiàn)自定義處理異常
交由ErrorViewResolver的情況 :
情況一: response.sendError ,error 請(qǐng)求轉(zhuǎn)給 Controller
情況二: 判斷異常請(qǐng)求無(wú)人處理,tomcat 底層 response.sendError
ErrorViewResolver處理方法:
BasicErrorController 得到要去的地址后由 ErrorViewResolver 解析,解析規(guī)則為拼接狀態(tài)碼等信息
—— 即 ErrorViewResolver 是最后的異常處理, 沒(méi)人處理的異常,被它處理
到此這篇關(guān)于SpringBoot自定義錯(cuò)誤處理邏輯詳解的文章就介紹到這了,更多相關(guān)SpringBoot錯(cuò)誤處理邏輯內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- SpringBoot錯(cuò)誤處理流程深入詳解
- SpringBoot2.1.4中的錯(cuò)誤處理機(jī)制
- Springboot實(shí)現(xiàn)自定義錯(cuò)誤頁(yè)面的方法(錯(cuò)誤處理機(jī)制)
- Springboot異常錯(cuò)誤處理解決方案詳解
- Springboot錯(cuò)誤處理機(jī)制實(shí)現(xiàn)原理解析
- SpringBoot錯(cuò)誤處理機(jī)制以及自定義異常處理詳解
- SpringBoot 錯(cuò)誤處理機(jī)制與自定義錯(cuò)誤處理實(shí)現(xiàn)詳解
- springboot 錯(cuò)誤處理小結(jié)
相關(guān)文章
java實(shí)現(xiàn)字符串四則運(yùn)算公式解析工具類(lèi)的方法
今天小編就為大家分享一篇java實(shí)現(xiàn)字符串四則運(yùn)算公式解析工具類(lèi)的方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2018-07-07java導(dǎo)出包含多個(gè)sheet的Excel代碼示例
這篇文章主要介紹了java導(dǎo)出包含多個(gè)sheet的Excel,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2019-03-03Java基礎(chǔ)知識(shí)之BufferedReader流的使用
這篇文章主要介紹了Java基礎(chǔ)知識(shí)之BufferedReader流的使用,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-12-12Mybatis中的mapper是如何和XMl關(guān)聯(lián)起來(lái)的
這篇文章主要介紹了Mybatis中的mapper是如何和XMl關(guān)聯(lián)起來(lái)的問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-06-06shiro與spring?security用自定義異常處理401錯(cuò)誤
這篇文章主要介紹了shiro與spring?security用自定義異常處理401錯(cuò)誤,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-11-11Java 圖片與byte數(shù)組互相轉(zhuǎn)換實(shí)例
下面小編就為大家?guī)?lái)一篇Java 圖片與byte數(shù)組互相轉(zhuǎn)換實(shí)例。小編覺(jué)得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2017-02-02JAVA數(shù)據(jù)結(jié)構(gòu)之漢諾塔代碼實(shí)例
這篇文章主要介紹了JAVA數(shù)據(jù)結(jié)構(gòu)之漢諾塔,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2019-04-04