告別死板錯(cuò)誤頁(yè)!Spring Boot 3.4 錯(cuò)誤頁(yè)面處理新特性實(shí)戰(zhàn)揭秘
在傳統(tǒng)的 Spring Boot 項(xiàng)目中,當(dāng)出現(xiàn) 404、500 等錯(cuò)誤時(shí),往往會(huì)展示一個(gè)千篇一律的白標(biāo)簽錯(cuò)誤頁(yè)(Whitelabel Error Page),不僅用戶體驗(yàn)差,還難以定位問題。隨著 Spring Boot 3.4 的發(fā)布,錯(cuò)誤處理機(jī)制迎來重大升級(jí)!
新版本不僅提供了更靈活的錯(cuò)誤頁(yè)面注冊(cè)方式,還支持通過 yaml
精準(zhǔn)控制錯(cuò)誤信息的返回行為,開發(fā)者可以輕松實(shí)現(xiàn):
- 自定義 JSON 錯(cuò)誤響應(yīng)結(jié)構(gòu)
- 異常類型與狀態(tài)碼的精細(xì)映射
- 前端頁(yè)面與 WebClient 的統(tǒng)一錯(cuò)誤感知與展示
本文將通過實(shí)戰(zhàn)示例,帶你全面掌握 Spring Boot 3.4 新增的錯(cuò)誤處理特性,打造既優(yōu)雅又專業(yè)的異常處理體系!
新特性一覽
精細(xì)化配置錯(cuò)誤信息展示:
# application.yaml
server:
error:
whitelabel:
enabled: false # 禁用默認(rèn)白標(biāo)簽錯(cuò)誤頁(yè)
include-message: always # 總是返回錯(cuò)誤信息
include-stacktrace: on_param # 請(qǐng)求帶 trace 參數(shù)時(shí)顯示堆棧
后端實(shí)戰(zhàn)代碼詳解
自定義統(tǒng)一錯(cuò)誤結(jié)構(gòu):CustomErrorAttributes
@Component
public class CustomErrorAttributes extends DefaultErrorAttributes {
// 重寫默認(rèn)錯(cuò)誤返回,構(gòu)造統(tǒng)一結(jié)構(gòu)的 JSON 響應(yīng)
@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;
}
}
注冊(cè)自定義錯(cuò)誤路徑:ErrorPageConfig
@Configuration
public class ErrorPageConfig implements ErrorPageRegistrar {
// 注冊(cè) 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")
);
}
}
映射錯(cuò)誤路徑響應(yīng)內(nèi)容: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, "服務(wù)器內(nèi)部錯(cuò)誤"));
}
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 頁(yè)面展示:error.html(Thymeleaf)
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>系統(tǒng)異常</title>
<link rel="stylesheet">
</head>
<body class="text-center mt-5">
<div class="container">
<h1 class="text-danger">出錯(cuò)啦!</h1>
<p th:text="'錯(cuò)誤信息:' + ${message}">錯(cuò)誤信息:服務(wù)器錯(cuò)誤</p>
<p th:text="'路徑:' + ${path}"></p>
<a class="btn btn-primary mt-3" href="/">返回首頁(yè)</a>
</div>
</body>
</html>
前后端聯(lián)調(diào)示例
前端 JS 捕獲統(tǒng)一錯(cuò)誤格式:
fetch('/api/test-error') // 故意請(qǐng)求一個(gè)異常接口
.then(res => res.json())
.then(data => {
if (data.code !== 200) {
alert("錯(cuò)誤:" + data.message + "\n路徑:" + data.path);
}
})
.catch(err => console.error("網(wǎng)絡(luò)異常", err));
模擬異常接口:
@RestController
@RequestMapping("/api")
public class TestController {
// 模擬后端接口異常
@GetMapping("/test-error")
public String triggerError() {
throw new RuntimeException("接口發(fā)生異常啦!");
}
}
總結(jié)
Spring Boot 3.4 所帶來的錯(cuò)誤處理新特性,不再是簡(jiǎn)單的“換個(gè)樣式”那么膚淺,而是從底層設(shè)計(jì)上為開發(fā)者提供了高度可定制的錯(cuò)誤響應(yīng)體系。
無論是 API 返回統(tǒng)一格式、頁(yè)面友好提示,還是前端異步請(qǐng)求的異常捕獲,這一機(jī)制都能完美支持。結(jié)合 WebClient
、Thymeleaf
與 Bootstrap,你可以輕松構(gòu)建出:
- 用戶看得懂的錯(cuò)誤提示
- 開發(fā)者排查便捷的錯(cuò)誤詳情
- 與前端高度協(xié)同的錯(cuò)誤處理流程
一個(gè)更現(xiàn)代、更穩(wěn)健的后端系統(tǒng),從告別死板錯(cuò)誤頁(yè)開始!