您好,登录后才能下订单哦!
密码登录
登录注册
点击 登录注册 即表示同意《亿速云用户服务条款》
# SpringBoot怎么自定义404、500错误提示页面
## 前言
在Web应用开发中,优雅的错误页面处理是提升用户体验的重要环节。SpringBoot默认提供了基础的错误页面(Whitelabel Error Page),但往往无法满足实际项目的需求。本文将详细介绍如何在SpringBoot中自定义404(资源不存在)、500(服务器内部错误)等常见HTTP错误页面,涵盖静态页面和动态模板两种实现方式。
---
## 一、SpringBoot默认错误处理机制
### 1.1 默认错误页面
当SpringBoot应用抛出异常或访问不存在的URL时,会显示如下白标错误页:
```html
Whitelabel Error Page
This application has no explicit mapping for /error...
BasicErrorController
会捕获请求/error
路径的映射Accept
头决定返回HTML或JSON响应server.error.path=/error # 错误处理路径
server.error.whitelabel.enabled=true # 是否启用默认白标页
在resources/static
下创建错误页面:
resources/
└── static/
├── error/
│ ├── 404.html
│ └── 500.html
<!DOCTYPE html>
<html>
<head>
<title>404 Not Found</title>
<style>
.container {
text-align: center;
margin-top: 100px;
}
.error-code {
font-size: 72px;
color: #ff4757;
}
</style>
</head>
<body>
<div class="container">
<h1 class="error-code">404</h1>
<p>您访问的资源不存在</p>
<a href="/">返回首页</a>
</div>
</body>
</html>
/not-exist
)支持更精确的状态码匹配:
resources/
└── static/
└── error/
├── 404.html
├── 5xx.html # 匹配所有5xx错误
└── 4xx.html # 匹配所有4xx错误
resources/
└── templates/
└── error/
├── 404.html
└── 500.html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title th:text="${error} + ' - 系统错误'">500 Error</title>
</head>
<body>
<div th:if="${timestamp}">
<h1 th:text="${error}">Error</h1>
<p th:text="${message}">Error message</p>
<p>错误时间:<span th:text="${#dates.format(timestamp, 'yyyy-MM-dd HH:mm')}"></span></p>
<p th:text="${path}"></p>
</div>
<a th:href="@{/}">返回首页</a>
</body>
</html>
属性名 | 说明 |
---|---|
timestamp | 错误发生时间 |
status | HTTP状态码 |
error | 错误原因 |
message | 详细错误信息 |
path | 请求路径 |
resources/
└── templates/
└── error.ftlh
示例内容:
<#-- 通用错误模板 -->
[#if status??]
<h1>${status} Error</h1>
[/#if]
${message!}
@Controller
@RequestMapping("${server.error.path:${error.path:/error}}")
public class CustomErrorController implements ErrorController {
@RequestMapping
public String handleError(HttpServletRequest request, Model model) {
Integer status = (Integer) request.getAttribute("javax.servlet.error.status_code");
switch(status) {
case 404:
model.addAttribute("customMsg", "您访问的页面去火星了");
return "error/404";
case 500:
model.addAttribute("customMsg", "服务器开小差了");
return "error/500";
default:
return "error/generic";
}
}
@Override
public String getErrorPath() {
return "/error";
}
}
@ExceptionHandler(Exception.class)
public ModelAndView handleAllExceptions(Exception ex, HttpServletRequest request) {
ModelAndView mav = new ModelAndView("error/500");
mav.addObject("exception", ex.getClass().getSimpleName());
mav.addObject("stackTrace", ex.getStackTrace());
return mav;
}
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(Exception.class)
public ResponseEntity<Map<String, Object>> handleException(HttpServletRequest request, Exception ex) {
Map<String, Object> body = new LinkedHashMap<>();
body.put("timestamp", LocalDateTime.now());
body.put("status", HttpStatus.INTERNAL_SERVER_ERROR.value());
if ("XMLHttpRequest".equals(request.getHeader("X-Requested-With"))) {
return new ResponseEntity<>(body, HttpStatus.INTERNAL_SERVER_ERROR);
}
return null; // 交由视图解析器处理
}
}
{
"success": false,
"code": 500,
"message": "Internal Server Error",
"data": null
}
用户体验优化:
开发建议:
# 开发环境显示详细错误
server.error.include-stacktrace=always
# 生产环境隐藏细节
server.error.include-stacktrace=never
SEO友好处理:
<meta name="robots" content="noindex">
HTTP缓存控制:
response.setHeader("Cache-Control", "no-cache, no-store");
自定义页面不生效:
server.error.path
配置动态模板无法获取错误信息:
AJAX请求处理异常:
X-Requested-With: XMLHttpRequest
@ExceptionHandler
优先级通过本文介绍的多种方式,开发者可以灵活实现SpringBoot应用的错误页面定制。建议根据项目实际需求选择合适方案: - 简单项目:静态HTML方案 - 复杂项目:模板引擎+自定义控制器 - 前后端分离:统一JSON格式处理
合理的错误处理不仅能提升用户体验,还能帮助开发者快速定位问题,是Web开发中不可忽视的重要环节。 “`
注:本文实际约2400字,包含了实现方案、代码示例、配置说明和最佳实践等内容,采用Markdown格式编写,可直接用于技术文档发布。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。