




版權說明:本文檔由用戶提供并上傳,收益歸屬內容提供方,若內容存在侵權,請進行舉報或認領
文檔簡介
第SpringBoot自定義錯誤處理邏輯詳解目錄1.自定義錯誤頁面2.@ControllerAdvice+@ExceptionHandler3.使用@ResponseStatus處理自定義異常4.框架底層異常5.自定義異常解析器6.ErrorViewResolver實現(xiàn)自定義處理異常
1.自定義錯誤頁面
將自定義錯誤頁面放在templates的error文件夾下,SpringBoot精確匹配錯誤信息,使用4xx.html或者5xx.html頁面可以打印錯誤信息
4xx打印status及message信息
h2th:text="${status}"pagenotfound/h2
h3th:text="${#message}"WeCouldn'tFindThisPage/h3
5xx打印message及trace信息
h3th:text="${message}"Somethingwentwrong./h3
pth:text="${trace}"WhynottryrefreshingyoupageOryoucanahref="#"rel="externalnofollow"contactoursupport/aiftheproblempersists./p
2.@ControllerAdvice+@ExceptionHandler
自定義全局異常處理類,處理ArithmeticException及NullPointerException異常
packagecom.wanqing.admin.exception;
importlombok.extern.slf4j.Slf4j;
importorg.springframework.web.bind.annotation.ControllerAdvice;
importorg.springframework.web.bind.annotation.ExceptionHandler;
@Slf4j
@ControllerAdvice//使用此注釋
publicclassGlobalExceptionHandler{
@ExceptionHandler({ArithmeticException.class,NullPointerException.class
})//使用此注釋,大括號內為可以處理的異常信息
publicStringhandleArithException(Exceptione){
("異常是:"+e);
return"login";//返回一個視圖地址(ModelAndView)
}
原理:
使用ExceptionHandlerExceptionResolver異常處理器處理用@ExceptionHandler注釋的異常
3.使用@ResponseStatus處理自定義異常
自定義異常類示例代碼:
importorg.springframework.http.HttpStatus;
importorg.springframework.web.bind.annotation.ResponseStatus;
@ResponseStatus(value=HttpStatus.FORBIDDEN,reason="用戶數(shù)量太多~~")//異??梢苑祷貭顟B(tài)碼信息
publicclassuserToManyextendsRuntimeException{
//有參構造器
publicuserToMany(Stringmessage){
super(message);
publicuserToMany(){
}
原理:
ResponseStatusExceptionResolver處理器可以處理@ResponseStatus注解的異常,得到@ResponseStatus注解的信息,調用response.sendError(statusCode)方法將錯誤信息返回,并發(fā)送/error請求,交由底層處理
sendError表示此次請求立刻結束,發(fā)出/error請求,SpringBoot找誰能處理,都不能處理返回默認的錯誤頁
protectedModelAndViewapplyStatusAndReason(intstatusCode,@NullableStringreason,HttpServletResponseresponse)throwsIOException{
if(!StringUtils.hasLength(reason)){
response.sendError(statusCode);
}else{
StringresolvedReason=this.messageSource!=nullthis.messageSource.getMessage(reason,(Object[])null,reason,LocaleContextHolder.getLocale()):reason;
response.sendError(statusCode,resolvedReason);
returnnewModelAndView();
}
4.框架底層異常
使用DefaultHandlerExceptionResolver異常處理器能處理SpringMVC底層異常,其能處理我異常種類如下
protectedModelAndViewdoResolveException(HttpServletRequestrequest,HttpServletResponseresponse,@NullableObjecthandler,Exceptionex){
try{
if(exinstanceofHttpRequestMethodNotSupportedException){
returnthis.handleHttpRequestMethodNotSupported((HttpRequestMethodNotSupportedException)ex,request,response,handler);
//此處省略
if(exinstanceofHttpMessageNotWritableException){
returnthis.handleHttpMessageNotWritable((HttpMessageNotWritableException)ex,request,response,handler);
if(exinstanceofMethodArgumentNotValidException){
returnthis.handleMethodArgumentNotValidException((MethodArgumentNotValidException)ex,request,response,handler);
}catch(Exceptionvar6){
if(this.logger.isWarnEnabled()){
this.logger.warn("Failurewhiletryingtoresolveexception["+ex.getClass().getName()+"]",var6);
returnnull;
}
5.自定義異常解析器
自定義異常解析器需要滿足以下:
實現(xiàn)HandlerExceptionResolver接口并注冊到容器中(@Component)在自定義解析器中實現(xiàn)resolveException方法,方法內可通過sendError方法返回錯誤信息并返回一空視圖,交給底層將錯誤信息解析拼接為最終頁面可以通過@Order注釋調整自定義異常解析器的優(yōu)先級,value越小優(yōu)先級越高
自定義異常解析器示例代碼:
importjavax.servlet.http.HttpServletResponse;
importjava.io.IOException;
@Order(value=Ordered.HIGHEST_PRECEDENCE)//優(yōu)先級數(shù)字越小,優(yōu)先級越高
@Component//注冊到容器中
publicclassCustomerHandlerResolverimplementsHandlerExceptionResolver{
@Override
publicModelAndViewresolveException(HttpServletRequesthttpServletRequest,HttpServletResponsehttpServletResponse,Objecto,Exceptione){
try{
httpServletResponse.sendError(511,"我不喜歡的錯誤");
}catch(IOExceptione1){
e1.printStackTrace();
returnnewModelAndView();
}
自定義異常處理器被加入(未調整優(yōu)先級時,默認加到最后):
6.ErrorViewResolver實現(xiàn)自定義處理異常
交由ErrorViewResolver的情況:
情況一:response.se
溫馨提示
- 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請下載最新的WinRAR軟件解壓。
- 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯(lián)系上傳者。文件的所有權益歸上傳用戶所有。
- 3. 本站RAR壓縮包中若帶圖紙,網頁內容里面會有圖紙預覽,若沒有圖紙預覽就沒有圖紙。
- 4. 未經權益所有人同意不得將文件中的內容挪作商業(yè)或盈利用途。
- 5. 人人文庫網僅提供信息存儲空間,僅對用戶上傳內容的表現(xiàn)方式做保護處理,對用戶上傳分享的文檔內容本身不做任何修改或編輯,并不能對任何下載內容負責。
- 6. 下載文件中如有侵權或不適當內容,請與我們聯(lián)系,我們立即糾正。
- 7. 本站不保證下載資源的準確性、安全性和完整性, 同時也不承擔用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。
最新文檔
- 2025年內部股東協(xié)議
- 腸炎護理常規(guī)
- 武則天介紹教學課件
- 高一年級下冊期中復習:選擇題(十七大題型)原卷版-2024-2025學年高一數(shù)學(人教A版必修第二冊)
- 肢端肥大癥的治療與護理
- 《溫室氣體 產品碳足跡量化方法與要求 橡膠管產品》標準編制說明
- 高考數(shù)學復習重難點題型:數(shù)列遞推求通項15類(原卷版)
- 護理培訓講課體系構建
- 兒科護理學試題及參考答案(二)
- 內科護理翻轉課堂
- 食品營養(yǎng)學(暨南大學)智慧樹知到答案章節(jié)測試2023年
- GA 1810-2022城鎮(zhèn)燃氣系統(tǒng)反恐怖防范要求
- GB/T 2518-2008連續(xù)熱鍍鋅鋼板及鋼帶
- GB/T 20145-2006燈和燈系統(tǒng)的光生物安全性
- 商戶撤場退鋪驗收單
- 手工皂制作教程(課堂)課件
- 部編版小學道德與法治三年級下冊期末質量檢測試卷【含答案】5套
- 斷親協(xié)議書范本
- 五年級語文下冊第八單元【教材解讀】課件
- 手衛(wèi)生依從性差魚骨分析
- 外科圍手術期患者心理問題原因分析及護理干預
評論
0/150
提交評論