SpringBoot自定義錯(cuò)誤處理邏輯詳解_第1頁
SpringBoot自定義錯(cuò)誤處理邏輯詳解_第2頁
SpringBoot自定義錯(cuò)誤處理邏輯詳解_第3頁
SpringBoot自定義錯(cuò)誤處理邏輯詳解_第4頁
SpringBoot自定義錯(cuò)誤處理邏輯詳解_第5頁
已閱讀5頁,還剩1頁未讀, 繼續(xù)免費(fèi)閱讀

下載本文檔

版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請(qǐng)進(jìn)行舉報(bào)或認(rèn)領(lǐng)

文檔簡介

第SpringBoot自定義錯(cuò)誤處理邏輯詳解目錄1.自定義錯(cuò)誤頁面2.@ControllerAdvice+@ExceptionHandler3.使用@ResponseStatus處理自定義異常4.框架底層異常5.自定義異常解析器6.ErrorViewResolver實(shí)現(xiàn)自定義處理異常

1.自定義錯(cuò)誤頁面

將自定義錯(cuò)誤頁面放在templates的error文件夾下,SpringBoot精確匹配錯(cuò)誤信息,使用4xx.html或者5xx.html頁面可以打印錯(cuò)誤信息

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

})//使用此注釋,大括號(hào)內(nèi)為可以處理的異常信息

publicStringhandleArithException(Exceptione){

("異常是:"+e);

return"login";//返回一個(gè)視圖地址(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{

//有參構(gòu)造器

publicuserToMany(Stringmessage){

super(message);

publicuserToMany(){

}

原理:

ResponseStatusExceptionResolver處理器可以處理@ResponseStatus注解的異常,得到@ResponseStatus注解的信息,調(diào)用response.sendError(statusCode)方法將錯(cuò)誤信息返回,并發(fā)送/error請(qǐng)求,交由底層處理

sendError表示此次請(qǐng)求立刻結(jié)束,發(fā)出/error請(qǐng)求,SpringBoot找誰能處理,都不能處理返回默認(rèn)的錯(cuò)誤頁

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.自定義異常解析器

自定義異常解析器需要滿足以下:

實(shí)現(xiàn)HandlerExceptionResolver接口并注冊(cè)到容器中(@Component)在自定義解析器中實(shí)現(xiàn)resolveException方法,方法內(nèi)可通過sendError方法返回錯(cuò)誤信息并返回一空視圖,交給底層將錯(cuò)誤信息解析拼接為最終頁面可以通過@Order注釋調(diào)整自定義異常解析器的優(yōu)先級(jí),value越小優(yōu)先級(jí)越高

自定義異常解析器示例代碼:

importjavax.servlet.http.HttpServletResponse;

importjava.io.IOException;

@Order(value=Ordered.HIGHEST_PRECEDENCE)//優(yōu)先級(jí)數(shù)字越小,優(yōu)先級(jí)越高

@Component//注冊(cè)到容器中

publicclassCustomerHandlerResolverimplementsHandlerExceptionResolver{

@Override

publicModelAndViewresolveException(HttpServletRequesthttpServletRequest,HttpServletResponsehttpServletResponse,Objecto,Exceptione){

try{

httpServletResponse.sendError(511,"我不喜歡的錯(cuò)誤");

}catch(IOExceptione1){

e1.printStackTrace();

returnnewModelAndView();

}

自定義異常處理器被加入(未調(diào)整優(yōu)先級(jí)時(shí),默認(rèn)加到最后):

6.ErrorViewResolver實(shí)現(xiàn)自定義處理異常

交由ErrorViewResolver的情況:

情況一:response.se

溫馨提示

  • 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請(qǐng)下載最新的WinRAR軟件解壓。
  • 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請(qǐng)聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
  • 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內(nèi)容里面會(huì)有圖紙預(yù)覽,若沒有圖紙預(yù)覽就沒有圖紙。
  • 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
  • 5. 人人文庫網(wǎng)僅提供信息存儲(chǔ)空間,僅對(duì)用戶上傳內(nèi)容的表現(xiàn)方式做保護(hù)處理,對(duì)用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對(duì)任何下載內(nèi)容負(fù)責(zé)。
  • 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請(qǐng)與我們聯(lián)系,我們立即糾正。
  • 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時(shí)也不承擔(dān)用戶因使用這些下載資源對(duì)自己和他人造成任何形式的傷害或損失。

評(píng)論

0/150

提交評(píng)論