SpringBoot自定義錯誤處理邏輯詳解
1. 自定義錯誤頁面
將自定義錯誤頁面放在 templates 的 error 文件夾下,SpringBoot 精確匹配錯誤信息,使用 4xx.html 或者 5xx.html 頁面可以打印錯誤信息
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
自定義全局異常處理類,處理 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
}) // 使用此注釋,大括號內(nèi)為可以處理的異常信息
public String handleArithException(Exception e){
log.info("異常是:" + e);
return "login"; // 返回一個視圖地址(ModelAndView)
}
}原理:
使用 ExceptionHandlerExceptionResolver 異常處理器處理用 @ExceptionHandler 注釋的異常

3. 使用@ResponseStatus處理自定義異常
自定義異常類示例代碼:
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;
@ResponseStatus(value = HttpStatus.FORBIDDEN, reason = "用戶數(shù)量太多~~") // 異常可以返回狀態(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) 方法將錯誤信息返回,并發(fā)送 /error 請求,交由底層處理
sendError —— 表示此次請求立刻結(jié)束,發(fā)出 /error 請求,SpringBoot 找誰能處理,都不能處理返回默認的錯誤頁
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 底層異常,其能處理我異常種類如下
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. 自定義異常解析器
自定義異常解析器需要滿足以下:
- 實現(xiàn) HandlerExceptionResolver 接口并注冊到容器中(@Component)
- 在自定義解析器中實現(xiàn) resolveException 方法,方法內(nèi)可通過 sendError 方法返回錯誤信息并返回一空視圖,交給底層將錯誤信息解析拼接為最終頁面
- 可以通過 @Order 注釋調(diào)整自定義異常解析器的優(yōu)先級,value越小優(yōu)先級越高
自定義異常解析器示例代碼:
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@Order(value = Ordered.HIGHEST_PRECEDENCE) // 優(yōu)先級數(shù)字越小,優(yōu)先級越高
@Component // 注冊到容器中
public class CustomerHandlerResolver implements HandlerExceptionResolver {
@Override
public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) {
try {
httpServletResponse.sendError(511, "我不喜歡的錯誤");
} catch (IOException e1){
e1.printStackTrace();
}
return new ModelAndView();
}
}自定義異常處理器被加入(未調(diào)整優(yōu)先級時,默認加到最后):

6. ErrorViewResolver實現(xiàn)自定義處理異常
交由ErrorViewResolver的情況 :
情況一: response.sendError ,error 請求轉(zhuǎn)給 Controller
情況二: 判斷異常請求無人處理,tomcat 底層 response.sendError
ErrorViewResolver處理方法:
BasicErrorController 得到要去的地址后由 ErrorViewResolver 解析,解析規(guī)則為拼接狀態(tài)碼等信息
—— 即 ErrorViewResolver 是最后的異常處理, 沒人處理的異常,被它處理
到此這篇關(guān)于SpringBoot自定義錯誤處理邏輯詳解的文章就介紹到這了,更多相關(guān)SpringBoot錯誤處理邏輯內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
解決Spring Security的權(quán)限配置不生效問題
這篇文章主要介紹了解決Spring Security的權(quán)限配置不生效問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-03-03
SpringBoot項目中使用騰訊云發(fā)送短信的實現(xiàn)
本文主要介紹了SpringBoot項目中使用騰訊云發(fā)送短信的實現(xiàn),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2023-04-04
Mybatis-plus新版本分頁失效PaginationInterceptor過時的問題
這篇文章主要介紹了Mybatis-plus新版本分頁失效,PaginationInterceptor過時問題,本文給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-11-11

