告別死板錯誤頁!Spring Boot 3.4 錯誤頁面處理新特性實戰揭秘
在傳統的 Spring Boot 項目中,當出現 404、500 等錯誤時,往往會展示一個千篇一律的白標簽錯誤頁(Whitelabel Error Page),不僅用戶體驗差,還難以定位問題。隨著 Spring Boot 3.4 的發布,錯誤處理機制迎來重大升級!
新版本不僅提供了更靈活的錯誤頁面注冊方式,還支持通過 yaml
精準控制錯誤信息的返回行為,開發者可以輕松實現:
- 自定義 JSON 錯誤響應結構
- 異常類型與狀態碼的精細映射
- 前端頁面與 WebClient 的統一錯誤感知與展示
本文將通過實戰示例,帶你全面掌握 Spring Boot 3.4 新增的錯誤處理特性,打造既優雅又專業的異常處理體系!
新特性一覽
精細化配置錯誤信息展示:
# application.yaml
server:
error:
whitelabel:
enabled: false # 禁用默認白標簽錯誤頁
include-message: always # 總是返回錯誤信息
include-stacktrace: on_param # 請求帶 trace 參數時顯示堆棧
后端實戰代碼詳解
自定義統一錯誤結構:CustomErrorAttributes
@Component
public class CustomErrorAttributes extends DefaultErrorAttributes {
// 重寫默認錯誤返回,構造統一結構的 JSON 響應
@Override
public Map<String, Object> getErrorAttributes(WebRequest webRequest, ErrorAttributeOptions options) {
Throwable error = getError(webRequest);
Map<String, Object> errorAttributes = new LinkedHashMap<>();
errorAttributes.put("code", HttpStatus.INTERNAL_SERVER_ERROR.value());
errorAttributes.put("message", error != null ? error.getMessage() : "Unexpected error occurred");
errorAttributes.put("timestamp", LocalDateTime.now());
errorAttributes.put("path", webRequest.getDescription(false).replace("uri=", ""));
return errorAttributes;
}
}
注冊自定義錯誤路徑:ErrorPageConfig
@Configuration
public class ErrorPageConfig implements ErrorPageRegistrar {
// 注冊 404 和 500 的自定義路徑
@Override
public void registerErrorPages(ErrorPageRegistry registry) {
registry.addErrorPages(
new ErrorPage(HttpStatus.NOT_FOUND, "/error/404"),
new ErrorPage(HttpStatus.INTERNAL_SERVER_ERROR, "/error/500")
);
}
}
映射錯誤路徑響應內容:CustomErrorController
@RestController
@RequestMapping("/error")
public class CustomErrorController {
@GetMapping("/404")
public ResponseEntity<Map<String, Object>> notFound() {
return ResponseEntity.status(HttpStatus.NOT_FOUND).body(errorResponse(404, "資源不存在"));
}
@GetMapping("/500")
public ResponseEntity<Map<String, Object>> serverError() {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(errorResponse(500, "服務器內部錯誤"));
}
private Map<String, Object> errorResponse(int code, String message) {
Map<String, Object> map = new HashMap<>();
map.put("code", code);
map.put("message", message);
map.put("timestamp", LocalDateTime.now());
return map;
}
}
HTML 頁面展示:error.html(Thymeleaf)
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>系統異常</title>
<link rel="stylesheet">
</head>
<body class="text-center mt-5">
<div class="container">
<h1 class="text-danger">出錯啦!</h1>
<p th:text="'錯誤信息:' + ${message}">錯誤信息:服務器錯誤</p>
<p th:text="'路徑:' + ${path}"></p>
<a class="btn btn-primary mt-3" href="/">返回首頁</a>
</div>
</body>
</html>
前后端聯調示例
前端 JS 捕獲統一錯誤格式:
fetch('/api/test-error') // 故意請求一個異常接口
.then(res => res.json())
.then(data => {
if (data.code !== 200) {
alert("錯誤:" + data.message + "\n路徑:" + data.path);
}
})
.catch(err => console.error("網絡異常", err));
模擬異常接口:
@RestController
@RequestMapping("/api")
public class TestController {
// 模擬后端接口異常
@GetMapping("/test-error")
public String triggerError() {
throw new RuntimeException("接口發生異常啦!");
}
}
總結
Spring Boot 3.4 所帶來的錯誤處理新特性,不再是簡單的“換個樣式”那么膚淺,而是從底層設計上為開發者提供了高度可定制的錯誤響應體系。
無論是 API 返回統一格式、頁面友好提示,還是前端異步請求的異常捕獲,這一機制都能完美支持。結合 WebClient
、Thymeleaf
與 Bootstrap,你可以輕松構建出:
- 用戶看得懂的錯誤提示
- 開發者排查便捷的錯誤詳情
- 與前端高度協同的錯誤處理流程
一個更現代、更穩健的后端系統,從告別死板錯誤頁開始!