Spring Boot 中的默認異常處理機制解析(如 /error 接口)
在 Spring Boot 中,為了簡化 Web 應(yīng)用的異常處理流程,它提供了一套默認的全局異常處理機制,其中最核心的就是 /error
接口。這個接口是 Spring Boot 提供的一個內(nèi)置錯誤頁面控制器(BasicErrorController),用于統(tǒng)一返回錯誤信息。
?? 一句話總結(jié):
? Spring Boot 默認使用
BasicErrorController
來處理所有未被捕獲的異常,并通過/error
接口返回結(jié)構(gòu)化的錯誤響應(yīng)或跳轉(zhuǎn)到錯誤頁面(如 HTML 頁面)。
?? 一、默認行為概覽
請求類型 | 返回內(nèi)容 |
---|---|
瀏覽器請求(HTML) | 跳轉(zhuǎn)到 /error 頁面(如 error.html ) |
API 請求(JSON/REST) | 返回 JSON 格式的錯誤信息 |
例如:
- 訪問一個不存在的路徑:
GET /not-found
- 控制器拋出未處理的異常 都會被 Spring Boot 的
/error
端點捕獲并處理。
??? 二、核心組件解析
1. BasicErrorController
這是 Spring Boot 默認提供的錯誤處理器,負責(zé)處理 /error
請求。
@Controller @RequestMapping("${server.error.path:${spring.mvc.async.request-timeout}}") public class BasicErrorController extends AbstractErrorController { ... }
- 默認路徑為
/error
(可通過server.error.path
配置修改) - 支持兩種響應(yīng)格式:
text/html
:返回 HTML 錯誤頁面(如error.html
)- 其他格式(如 JSON):返回結(jié)構(gòu)化錯誤信息
2. ErrorAttributes 接口
該接口定義了錯誤信息的內(nèi)容來源,包括:
- 異常對象
- HTTP 狀態(tài)碼
- 請求 URL
- 時間戳等
默認實現(xiàn)是 DefaultErrorAttributes
,你也可以自定義。
3. ErrorViewResolver 接口
用于解析 HTML 錯誤頁面。例如:
/templates/error/404.html
/templates/error/5xx.html
/templates/error.html
Spring Boot 會根據(jù)狀態(tài)碼優(yōu)先匹配具體頁面。
?? 三、默認返回的 JSON 錯誤結(jié)構(gòu)
當(dāng)你訪問一個 REST 接口時,如果發(fā)生異常且沒有被 @ExceptionHandler
或 @ControllerAdvice
捕獲,Spring Boot 會返回如下格式的 JSON 響應(yīng):
{ "timestamp": "2025-07-12T10:45:00.000+00:00", "status": 404, "error": "Not Found", "path": "/not-found" }
字段說明:
字段名 | 含義 |
---|---|
timestamp | 錯誤發(fā)生時間 |
status | HTTP 狀態(tài)碼 |
error | 錯誤描述 |
exception | 異常類名(僅當(dāng) spring.boot.debug=true 時顯示) |
message | 異常消息(可選) |
path | 出錯的請求路徑 |
?? 四、如何自定義錯誤處理?
雖然 Spring Boot 提供了默認的錯誤處理機制,但在實際項目中我們通常需要進行定制:
1. 方式一:自定義 ErrorAttributes
你可以實現(xiàn) ErrorAttributes
接口來自定義錯誤信息內(nèi)容:
@Component public class CustomErrorAttributes extends DefaultErrorAttributes { @Override public Map<String, Object> getErrorAttributes(WebRequest webRequest, ErrorAttributeOptions options) { Map<String, Object> errorMap = super.getErrorAttributes(webRequest, options); errorMap.put("customInfo", "This is a custom error info."); return errorMap; } }
2. 方式二:繼承 BasicErrorController 自定義控制器
@RestController @RequestMapping("${server.error.path:/error}") public class CustomErrorController extends BasicErrorController { public CustomErrorController(ErrorAttributes errorAttributes) { super(errorAttributes, new ErrorProperties()); } @Override public ResponseEntity<Map<String, Object>> error(HttpServletRequest request) { Map<String, Object> body = getErrorAttributes(new ServletWebRequest(request), true); return new ResponseEntity<>(body, HttpStatus.INTERNAL_SERVER_ERROR); } }
3. 方式三:創(chuàng)建自定義錯誤頁面(HTML)
將 HTML 頁面放在以下位置之一即可:
src/main/resources/templates/error/404.html
src/main/resources/static/error/500.html
src/main/resources/public/error.html
Spring Boot 會根據(jù) HTTP 狀態(tài)碼自動選擇對應(yīng)的頁面。
4. 方式四:使用 @ControllerAdvice 全局處理異常
@RestControllerAdvice public class GlobalExceptionHandler { @ExceptionHandler(Exception.class) public ResponseEntity<Map<String, Object>> handleException(Exception ex, HttpServletRequest request) { Map<String, Object> errorBody = new HashMap<>(); errorBody.put("error", ex.getMessage()); errorBody.put("path", request.getRequestURI()); return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(errorBody); } }
這種方式比默認機制更靈活,適用于大型項目。
?? 五、配置相關(guān)屬性(application.yml)
你可以在 application.yml
或 application.properties
中配置一些與錯誤相關(guān)的參數(shù):
spring: mvc: async: request-timeout: 0 # 禁用超時控制 server: error: path: /my-error # 自定義錯誤路徑 whitelabel: enabled: false # 關(guān)閉默認白標(biāo)錯誤頁
? 六、總結(jié)
項目 | 內(nèi)容 |
---|---|
默認錯誤端點 | /error |
默認控制器 | BasicErrorController |
默認錯誤信息 | DefaultErrorAttributes |
默認視圖支持 | 支持 HTML 錯誤頁面(按狀態(tài)碼命名) |
JSON 輸出格式 | 包含 timestamp, status, error, path 等字段 |
可擴展性 | 支持自定義 ErrorAttributes、ErrorController、HTML 頁面、@ControllerAdvice |
到此這篇關(guān)于Spring Boot 中的默認異常處理機制(如 /error 接口)的文章就介紹到這了,更多相關(guān)Spring Boot 異常處理內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
常用json與javabean互轉(zhuǎn)的方法實現(xiàn)
這篇文章主要介紹了常用json與javabean互轉(zhuǎn)的方法實現(xiàn),文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-04-04