序言:此前,我們主要通過(guò)在控制層(Controller)中手動(dòng)捕捉異常(TryCatch)和處理錯(cuò)誤,在SpringBoot 統(tǒng)一異常處理的做法主要有兩種:一是基于注解ExceptionHandler,二是基于接口ErrorController,兩者都可以讓控制器層代碼快速“瘦身”,讓業(yè)務(wù)邏輯看起來(lái)更加清晰明朗! 本工程傳送門(mén):SpringBoot-Exception-Handler
一. 默認(rèn)錯(cuò)誤處理
SpringBoot 默認(rèn)為我們提供了BasicErrorController 來(lái)處理全局錯(cuò)誤/異常,并在Servlet容器中注冊(cè)error為全局錯(cuò)誤頁(yè)。所以在瀏覽器端訪問(wèn),發(fā)生錯(cuò)誤時(shí),我們能及時(shí)看到錯(cuò)誤/異常信息和HTTP狀態(tài)等反饋。工作原理如下:
@Controller
@RequestMapping("${server.error.path:${error.path:/error}}")
public class BasicErrorController extends AbstractErrorController {
// 統(tǒng)一異常處理(View)
@RequestMapping(produces = "text/html")
public ModelAndView errorHtml(HttpServletRequest request,
HttpServletResponse response) {
HttpStatus status = getStatus(request);
Map<String, Object> model = Collections.unmodifiableMap(getErrorAttributes(
request, isIncludeStackTrace(request, MediaType.TEXT_HTML)));
response.setStatus(status.value());
ModelAndView modelAndView = resolveErrorView(request, response, status, model);
return (modelAndView == null ? new ModelAndView("error", model) : modelAndView);
}
例如下面這兩個(gè)錯(cuò)誤,對(duì)于日常開(kāi)發(fā)而言,再熟悉不過(guò)了。


二. 統(tǒng)一異常處理
默認(rèn)的英文空白頁(yè),顯然不能夠滿足我們復(fù)雜多變的需求,因此我們可以通過(guò)專(zhuān)門(mén)的類(lèi)來(lái)收集和管理這些異常信息,這樣做不僅可以減少控制層的代碼量,還有利于線上故障排查和緊急短信通知等。
具體步驟
為了讓小伙伴少走一些彎路,樓主根據(jù)官方源碼和具體實(shí)踐,提煉這些核心工具類(lèi):
- ErrorInfo 錯(cuò)誤信息
- ErrorInfoBuilder 錯(cuò)誤信息的構(gòu)建工具
注:在CSDN和大牛博客中,不乏關(guān)于Web應(yīng)用的統(tǒng)一異常處理的教程,但更多的是基礎(chǔ)學(xué)習(xí)使用,并不能投入實(shí)際項(xiàng)目使用,為了讓大家少走一些彎路和快速投入生產(chǎn),樓主根據(jù)官方源碼和項(xiàng)目實(shí)踐,提煉出了核心工具類(lèi)(ErrorInfoBuilder ),將構(gòu)建異常信息的邏輯從異常處理器/控制器中抽離出來(lái),讓大家通過(guò)短短幾行代碼就能獲取豐富的異常信息,更專(zhuān)注于業(yè)務(wù)開(kāi)發(fā)??!
1. 統(tǒng)一異常處理器(GlobalErrorHandler)
@ControllerAdvice 限定范圍 例如掃描某個(gè)控制層的包
-
@ExceptionHandler 指定異常 例如指定處理運(yùn)行異常。
具體如下:
package com.hehe.error;
@ControllerAdvice
public class GlobalErrorHandler {
private final static String DEFAULT_ERROR_VIEW = "error";//錯(cuò)誤信息頁(yè)
@Autowired
private ErrorInfoBuilder errorInfoBuilder;//錯(cuò)誤信息的構(gòu)建工具
/**
* 根據(jù)業(yè)務(wù)規(guī)則,統(tǒng)一處理異常。
*/
@ExceptionHandler(Exception.class)
@ResponseBody
public Object exceptionHandler(HttpServletRequest request, Throwable error) {
//1.若為AJAX請(qǐng)求,則返回異常信息(JSON)
if (isAjaxRequest(request)) {
return errorInfoBuilder.getErrorInfo(request,error);
}
//2.其余請(qǐng)求,則返回指定的異常信息頁(yè)(View).
return new ModelAndView(DEFAULT_ERROR_VIEW, "errorInfo", errorInfoBuilder.getErrorInfo(request, error));
}
private boolean isAjaxRequest(HttpServletRequest request) {
return "XMLHttpRequest".equals(request.getHeader("X-Requested-With"));
}
}
2. 統(tǒng)一異常信息(ErrorInfo)
雖然官方提供了ErrorAttributes來(lái)存儲(chǔ)錯(cuò)誤信息,但其返回的是存儲(chǔ)結(jié)構(gòu)是Map<String,Object>,為了更好的服務(wù)統(tǒng)一異常,這里我們統(tǒng)一采用標(biāo)準(zhǔn)的ErrroInfo來(lái)記載錯(cuò)誤信息。
package com.hehe.error;
public class ErrorInfo {
private String time;//發(fā)生時(shí)間
private String url;//訪問(wèn)Url
private String error;//錯(cuò)誤類(lèi)型
String stackTrace;//錯(cuò)誤的堆棧軌跡
private int statusCode;//狀態(tài)碼
private String reasonPhrase;//狀態(tài)碼
//Getters And Setters
...
}
3. 統(tǒng)一異常信息的構(gòu)建工具(ErrorInfoBuilder)
ErrorInfoBuilder 作為核心工具類(lèi),其意義不言而喻,重點(diǎn)API:
獲取錯(cuò)誤/異常
通信狀態(tài)
堆棧軌跡
注:正確使用ErrorInfoBuilder,可以讓處理器減少80%的代碼??偠灾珽rrorInfoBuilder是個(gè)好東西,值得大家細(xì)細(xì)琢磨。
package com.hehe.error;
@Order(Ordered.HIGHEST_PRECEDENCE)
@Component
public class ErrorInfoBuilder implements HandlerExceptionResolver, Ordered {
/**
* 錯(cuò)誤KEY
*/
private final static String ERROR_NAME = "hehe.error";
/**
* 錯(cuò)誤配置(ErrorConfiguration)
*/
private ErrorProperties errorProperties;
public ErrorProperties getErrorProperties() {
return errorProperties;
}
public void setErrorProperties(ErrorProperties errorProperties) {
this.errorProperties = errorProperties;
}
/**
* 錯(cuò)誤構(gòu)造器 (Constructor) 傳遞配置屬性:server.xx -> server.error.xx
*/
public ErrorInfoBuilder(ServerProperties serverProperties) {
this.errorProperties = serverProperties.getError();
}
/**
* 構(gòu)建錯(cuò)誤信息.(ErrorInfo)
*/
public ErrorInfo getErrorInfo(HttpServletRequest request) {
return getErrorInfo(request, getError(request));
}
/**
* 構(gòu)建錯(cuò)誤信息.(ErrorInfo)
*/
public ErrorInfo getErrorInfo(HttpServletRequest request, Throwable error) {
ErrorInfo errorInfo = new ErrorInfo();
errorInfo.setTime(LocalDateTime.now().toString());
errorInfo.setUrl(request.getRequestURL().toString());
errorInfo.setError(error.toString());
errorInfo.setStatusCode(getHttpStatus(request).value());
errorInfo.setReasonPhrase(getHttpStatus(request).getReasonPhrase());
errorInfo.setStackTrace(getStackTraceInfo(error, isIncludeStackTrace(request)));
return errorInfo;
}
/**
* 獲取錯(cuò)誤.(Error/Exception)
*
* @see DefaultErrorAttributes #addErrorDetails
*/
public Throwable getError(HttpServletRequest request) {
//根據(jù)HandlerExceptionResolver接口方法來(lái)獲取錯(cuò)誤.
Throwable error = (Throwable) request.getAttribute(ERROR_NAME);
//根據(jù)Request對(duì)象獲取錯(cuò)誤.
if (error == null) {
error = (Throwable) request.getAttribute(WebUtils.ERROR_EXCEPTION_ATTRIBUTE);
}
//當(dāng)獲取錯(cuò)誤非空,取出RootCause.
if (error != null) {
while (error instanceof ServletException && error.getCause() != null) {
error = error.getCause();
}
}//當(dāng)獲取錯(cuò)誤為null,此時(shí)我們?cè)O(shè)置錯(cuò)誤信息即可.
else {
String message = (String) request.getAttribute(WebUtils.ERROR_MESSAGE_ATTRIBUTE);
if (StringUtils.isEmpty(message)) {
HttpStatus status = getHttpStatus(request);
message = "Unknown Exception But " + status.value() + " " + status.getReasonPhrase();
}
error = new Exception(message);
}
return error;
}
/**
* 獲取通信狀態(tài)(HttpStatus)
*
* @see AbstractErrorController #getStatus
*/
public HttpStatus getHttpStatus(HttpServletRequest request) {
Integer statusCode = (Integer) request.getAttribute(WebUtils.ERROR_STATUS_CODE_ATTRIBUTE);
try {
return statusCode != null ? HttpStatus.valueOf(statusCode) : HttpStatus.INTERNAL_SERVER_ERROR;
} catch (Exception ex) {
return HttpStatus.INTERNAL_SERVER_ERROR;
}
}
/**
* 獲取堆棧軌跡(StackTrace)
*
* @see DefaultErrorAttributes #addStackTrace
*/
public String getStackTraceInfo(Throwable error, boolean flag) {
if (!flag) {
return "omitted";
}
StringWriter stackTrace = new StringWriter();
error.printStackTrace(new PrintWriter(stackTrace));
stackTrace.flush();
return stackTrace.toString();
}
/**
* 判斷是否包含堆棧軌跡.(isIncludeStackTrace)
*
* @see BasicErrorController #isIncludeStackTrace
*/
public boolean isIncludeStackTrace(HttpServletRequest request) {
//讀取錯(cuò)誤配置(server.error.include-stacktrace=NEVER)
IncludeStacktrace includeStacktrace = errorProperties.getIncludeStacktrace();
//情況1:若IncludeStacktrace為ALWAYS
if (includeStacktrace == IncludeStacktrace.ALWAYS) {
return true;
}
//情況2:若請(qǐng)求參數(shù)含有trace
if (includeStacktrace == IncludeStacktrace.ON_TRACE_PARAM) {
String parameter = request.getParameter("trace");
return parameter != null && !"false".equals(parameter.toLowerCase());
}
//情況3:其它情況
return false;
}
/**
* 保存錯(cuò)誤/異常.
*
* @see DispatcherServlet #processHandlerException 進(jìn)行選舉HandlerExceptionResolver
*/
@Override
public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, @Nullable Object handler, Exception ex) {
request.setAttribute(ERROR_NAME, ex);
return null;
}
/**
* 提供優(yōu)先級(jí) 或用于排序
*/
@Override
public int getOrder() {
return Ordered.HIGHEST_PRECEDENCE;
}
}
注:ErrorBuilder之所以使用@Order注解和實(shí)現(xiàn)HandlerExceptionResolver接口是為了獲取錯(cuò)誤/異常,通常情況下@ExceptionHandler并不需要這么做,因?yàn)樵谟成浞椒ㄗ⑷隩hrowable就可以獲得錯(cuò)誤/異常,這是主要是為了ErrorController根據(jù)Request對(duì)象快速獲取錯(cuò)誤/異常。
4. 控制層代碼(Controller)
上述,錯(cuò)誤/異常處理器、錯(cuò)誤信息、錯(cuò)誤信息構(gòu)建工具全部完成,我們編寫(xiě)控制層代碼來(lái)測(cè)試相關(guān)效果。
package com.hehe;
@SpringBootApplication
@RestController
public class ErrorHandlerApplication {
/**
* 隨機(jī)拋出異常
*/
private void randomException() throws Exception {
Exception[] exceptions = { //異常集合
new NullPointerException(),
new ArrayIndexOutOfBoundsException(),
new NumberFormatException(),
new SQLException()};
//發(fā)生概率
double probability = 0.75;
if (Math.random() < probability) {
//情況1:要么拋出異常
throw exceptions[(int) (Math.random() * exceptions.length)];
} else {
//情況2:要么繼續(xù)運(yùn)行
}
}
/**
* 模擬用戶數(shù)據(jù)訪問(wèn)
*/
@GetMapping("/")
public List index() throws Exception {
randomException();
return Arrays.asList("正常用戶數(shù)據(jù)1!", "正常用戶數(shù)據(jù)2! 請(qǐng)按F5刷新!!");
}
public static void main(String[] args) {
SpringApplication.run(ErrorHandlerApplication.class, args);
}
}
5. 頁(yè)面代碼(Thymeleaf)
代碼完成之后,我們需要編寫(xiě)一個(gè)異常信息頁(yè)面。為了方便演示,我們?cè)趓esources目錄下創(chuàng)建templates目錄,并新建文件exception.html。頁(yè)面代碼如下:
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>GlobalError</title>
</head>
<h1>統(tǒng)一祖國(guó) 振興中華</h1>
<h2>服務(wù)異常,請(qǐng)稍后再試。</h2>
<div th:object="${errorInfo}">
<h3 th:text="*{'發(fā)生時(shí)間:'+time}"></h3>
<h3 th:text="*{'訪問(wèn)地址:'+url}"></h3>
<h3 th:text="*{'問(wèn)題類(lèi)型:'+error}"></h3>
<h3 th:text="*{'通信狀態(tài):'+statusCode+','+reasonPhrase}"></h3>
<h3 th:text="*{'堆棧信息:'+stackTrace}"></h3>
</div>
</body>
</html>
注:SpringBoot默認(rèn)支持很多種模板引擎(如Thymeleaf、FreeMarker),并提供了相應(yīng)的自動(dòng)配置,做到開(kāi)箱即用。默認(rèn)的頁(yè)面加載路徑是 src/main/resources/templates ,如果放到其它目錄需在配置文件指定。(舉例:spring.thymeleaf.prefix=classpath:/views/ )
6. 引入依賴(lài)(POM文件)
以前操作之前,不要忘了在pom.xml 引入相關(guān)依賴(lài):
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<!--基本信息 -->
<groupId>com.hehe</groupId>
<artifactId>springboot-error-handler</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>spring-boot-error-handler</name>
<description>SpringBoot 統(tǒng)一異常處理</description>
<!--繼承信息 -->
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.0.M4</version>
<relativePath/>
</parent>
<!--依賴(lài)管理 -->
<dependencies>
<dependency> <!--添加Web依賴(lài) -->
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency> <!--添加Thymeleaf依賴(lài) -->
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency><!--添加Test依賴(lài) -->
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<!--指定遠(yuǎn)程倉(cāng)庫(kù)(含插件)-->
<repositories>
<repository>
<id>spring-snapshots</id>
<url>http://repo.spring.io/snapshot</url>
<snapshots>
<enabled>true</enabled>
</snapshots>
</repository>
<repository>
<id>spring-milestones</id>
<url>http://repo.spring.io/milestone</url>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>spring-snapshots</id>
<url>http://repo.spring.io/snapshot</url>
</pluginRepository>
<pluginRepository>
<id>spring-milestones</id>
<url>http://repo.spring.io/milestone</url>
</pluginRepository>
</pluginRepositories>
<!--構(gòu)建插件 -->
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
7. 開(kāi)始測(cè)試
上述步驟完成之后,打開(kāi)啟動(dòng)類(lèi)GlobalExceptionApplication,啟動(dòng)項(xiàng)目然后進(jìn)行測(cè)試。本案例-項(xiàng)目結(jié)構(gòu)圖如下:

測(cè)試效果:在瀏覽器輸入 http://localhost:8080 多次按F5刷新,然后查看頁(yè)面效果。截圖如下:

三. 使用@ExceptionHandler的不足之處
關(guān)于實(shí)現(xiàn)Web應(yīng)用統(tǒng)一異常處理的兩種方法比較:
| 特性 | @ExceptionHandler | ErrorController |
|---|---|---|
| 獲取異常 | 通過(guò)方法參數(shù)注入 | 通過(guò)ErrorInfoBuilder獲取 |
| 返回類(lèi)型 | 若請(qǐng)求的類(lèi)型為Ajax則返回JSON,否則返回頁(yè)面. | 若請(qǐng)求的媒介類(lèi)型為HTML 則返回頁(yè)面 ,否則返回JSON. |
| 缺點(diǎn) | 無(wú)法處理404類(lèi)異常 | 很強(qiáng)大,可處理全部錯(cuò)誤/異常 |
1. 使用@ExceptionHandler 為什么無(wú)法處理404錯(cuò)誤/異常?
- 答:因?yàn)镾pringMVC優(yōu)先處理(Try Catch)掉了資源映射不存在的404類(lèi)錯(cuò)誤/異常,雖然在響應(yīng)信息注入了404的HttpStatus通信信息,但木有了異常,肯定不會(huì)進(jìn)入@ExceptionHandler 的處理邏輯。
2. 使用@ExceptionHandler + 拋出異常 是否可???
- 答:由上圖可知@ExceptionHanlder的最大不足之處是無(wú)法直接捕獲404背后的異常,網(wǎng)上流傳通過(guò)取消資源目錄映射來(lái)解決無(wú)404問(wèn)題是不可取的,屬于越俎代庖的做法。
spring.mvc.throw-exception-if-no-handler-found=true
spring.resources.add-mappings=false
3. 為什么推薦ErrorController 替代 @ExceptionHandler ?
- 使用ErrorController可以處理 全部錯(cuò)誤/異常 。
- 使用ErrorController+ErrorInfoBuilder 在單個(gè)方法里面可以針對(duì)不同的Exception來(lái)添加詳細(xì)的錯(cuò)誤信息,具體做法:拓展ErrorInfoBuilder的getErrorInfo方法來(lái)添加錯(cuò)誤信息(例如:ex instanceof NullPointerException Set xxx)。
注意:實(shí)際上,目前SpringBoot官方就是通過(guò)ErrorController來(lái)做的統(tǒng)一錯(cuò)誤/異常處理,但遺憾的是,關(guān)于這方面的官方文檔并沒(méi)有給出詳細(xì)示例,僅僅是一筆帶過(guò),大概官方認(rèn)為@ExceptionHandler 夠用??而網(wǎng)上也甚少人具體提及ErrorController和ErrorAttribute 背后一整套的實(shí)現(xiàn)邏輯,也正是如此,促使樓主決心寫(xiě)下這篇文章,希望給大家?guī)?lái)幫助,少走一些彎路?。?/p>
四. 使用ErrorController替代@ExceptionHandler
4. 如何快速使用 ErrorController ?
回答:經(jīng)過(guò)樓主的精心設(shè)計(jì),ErrorInfoBuilder 可以無(wú)縫對(duì)接ErrorController (即上述兩種錯(cuò)誤/異常處理均共用此工具類(lèi)),你只需要做的是:將本案例的ErrorInfo和ErrorInfoBuilder 拷貝進(jìn)項(xiàng)目,簡(jiǎn)單編寫(xiě)ErrorController 跳轉(zhuǎn)頁(yè)面和返回JSON即可。具體如下:
- @RequestMapping(produces = MediaType.TEXT_HTML_VALUE)
說(shuō)明:produces屬性作為匹配規(guī)則:表示Request請(qǐng)求的Accept頭部需含有text/html。
用途:text/html 主要用于響應(yīng)普通的頁(yè)面請(qǐng)求,與AJAX請(qǐng)求作為區(qū)分。
package com.hehe.error;
@Controller
@RequestMapping("${server.error.path:/error}")
public class GlobalErrorController implements ErrorController {
@Autowired
private ErrorInfoBuilder errorInfoBuilder;//錯(cuò)誤信息的構(gòu)建工具.
private final static String DEFAULT_ERROR_VIEW = "error";//錯(cuò)誤信息頁(yè)
/**
* 情況1:若預(yù)期返回類(lèi)型為text/html,則返回錯(cuò)誤信息頁(yè)(View).
*/
@RequestMapping(produces = MediaType.TEXT_HTML_VALUE)
public ModelAndView errorHtml(HttpServletRequest request) {
return new ModelAndView(DEFAULT_ERROR_VIEW, "errorInfo", errorInfoBuilder.getErrorInfo(request));
}
/**
* 情況2:其它預(yù)期類(lèi)型 則返回詳細(xì)的錯(cuò)誤信息(JSON).
*/
@RequestMapping
@ResponseBody
public ErrorInfo error(HttpServletRequest request) {
return errorInfoBuilder.getErrorInfo(request);
}
@Override
public String getErrorPath() {//獲取映射路徑
return errorInfoBuilder.getErrorProperties().getPath();
}
}
注:是不是非常簡(jiǎn)單,相信這個(gè)工具類(lèi)可以改變你對(duì)ErrorController復(fù)雜難用的看法。如果后續(xù)想拓展不同種類(lèi)的錯(cuò)誤/異常信息,只需修改ErrorInfoBuilder#getError方法即可,無(wú)需修改ErrorController的代碼,十分方便。
五. 源碼和文檔
源碼下載:SpringBoot-ErrorController
源碼下載:SpringBoot-ExceptionHandler
專(zhuān)題閱讀:《SpringBoot 布道系列》