




版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請進(jìn)行舉報或認(rèn)領(lǐng)
文檔簡介
第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
})//使用此注釋,大括號內(nèi)為可以處理的異常信息
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{
//有參構(gòu)造器
publicuserToMany(Stringmessage){
super(message);
publicuserToMany(){
}
原理:
ResponseStatusExceptionResolver處理器可以處理@ResponseStatus注解的異常,得到@ResponseStatus注解的信息,調(diào)用response.sendError(statusCode)方法將錯誤信息返回,并發(fā)送/error請求,交由底層處理
sendError表示此次請求立刻結(jié)束,發(fā)出/error請求,SpringBoot找誰能處理,都不能處理返回默認(rèn)的錯誤頁
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方法,方法內(nèi)可通過sendError方法返回錯誤信息并返回一空視圖,交給底層將錯誤信息解析拼接為最終頁面可以通過@Order注釋調(diào)整自定義異常解析器的優(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();
}
自定義異常處理器被加入(未調(diào)整優(yōu)先級時,默認(rèn)加到最后):
6.ErrorViewResolver實現(xiàn)自定義處理異常
交由ErrorViewResolver的情況:
情況一:response.se
溫馨提示
- 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請下載最新的WinRAR軟件解壓。
- 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
- 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內(nèi)容里面會有圖紙預(yù)覽,若沒有圖紙預(yù)覽就沒有圖紙。
- 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
- 5. 人人文庫網(wǎng)僅提供信息存儲空間,僅對用戶上傳內(nèi)容的表現(xiàn)方式做保護(hù)處理,對用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對任何下載內(nèi)容負(fù)責(zé)。
- 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請與我們聯(lián)系,我們立即糾正。
- 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時也不承擔(dān)用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。
最新文檔
- 紡織品設(shè)計師的職業(yè)發(fā)展道路與挑戰(zhàn)研究試題及答案
- 餐飲合同協(xié)議書范本
- 雜工合同協(xié)議書
- 施工合同協(xié)議書合同編號
- 項目協(xié)議書合同
- 快遞合資合同協(xié)議書
- 馬口鐵合同協(xié)議書
- 購買肥牛合同協(xié)議書
- 拆除圍墻合同協(xié)議書
- 合伙開公司合同協(xié)議書
- 00510秘書實務(wù)-自考整合版
- 護(hù)理研究中的偏倚及控制
- 小學(xué)生的齲齒預(yù)防ppt課件
- [復(fù)習(xí)]邊坡客土吹附施工方案
- 門禁一卡通系統(tǒng)解決方案
- 沖壓試題庫及答案文檔
- 煤礦機電運輸專業(yè)質(zhì)量標(biāo)準(zhǔn)化管理制度
- 華為保密制度范文
- 凍庫溫度記錄表
- 工程款支付審核記錄表
- 成套開關(guān)柜GGD樣本
評論
0/150
提交評論