Tomcat/Spring Boot应用如何优雅处理500错误?3种自定义错误页配置实战
最近在排查一个线上问题时,我遇到了一个典型的场景:用户反馈某个功能报错,但页面上只显示了一堆看不懂的Java堆栈信息,用户完全不知道发生了什么,只能截图发给我们。更糟糕的是,堆栈信息里还包含了数据库连接字符串的片段——虽然只是部分,但这已经足够让人心惊胆战了。这种体验对用户来说极其糟糕,对我们开发者来说更是安全隐患。
在Java Web开发中,Tomcat和Spring Boot是两大主流技术栈。无论是传统的WAR包部署到Tomcat,还是Spring Boot的嵌入式容器,错误页面的处理都是生产环境必须重视的一环。一个设计良好的错误页面不仅能提升用户体验,更能有效防止敏感信息泄露,避免给攻击者留下可乘之机。
很多开发者认为配置个404页面就万事大吉了,但实际上这远远不够。HTTP状态码从400到500系列,每个都可能暴露不同的信息。特别是500内部服务器错误,如果不加处理,Tomcat默认会返回完整的异常堆栈,这里面可能包含SQL语句、文件路径、配置信息等敏感内容。我见过不少团队在开发测试环境为了方便调试,开启了详细错误信息,结果上线时忘记关闭,直接导致了信息泄露。
这篇文章我将结合多年实战经验,为你详细解析Tomcat和Spring Boot框架下,如何系统性地处理错误页面,特别是500错误的优雅处理方案。我会从原理到实践,提供三种不同层次的解决方案,并分享一些容易踩坑的细节。
1. 为什么仅仅配置404页面远远不够?
在开始具体的技术实现之前,我们需要先理解为什么错误页面处理如此重要。很多团队只配置了404页面,觉得用户访问不存在的页面时有个友好提示就够了,但这种想法存在几个严重的误区。
首先,错误类型远不止404一种。HTTP状态码主要分为几个大类:
- 4xx客户端错误:400错误请求、401未授权、403禁止访问、404未找到、405方法不允许等
- 5xx服务器端错误:500内部服务器错误、502错误网关、503服务不可用、504网关超时等
每一类错误都需要不同的处理方式。比如403错误可能需要引导用户登录或申请权限,503错误可能需要提示用户稍后重试。
其次,500错误是最危险的信息泄露源。当服务器端代码抛出未捕获的异常时,Tomcat默认会返回一个包含完整堆栈跟踪的错误页面。这个页面会暴露:
// 可能暴露的信息示例
com.example.dao.UserDAO.getUserById(UserDAO.java:45) // 类名、方法名、行号
at com.example.service.UserService.findUser(UserService.java:23)
Caused by: java.sql.SQLException: Connection refused // 数据库异常信息
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1074)
// 可能包含连接字符串片段:jdbc:mysql://localhost:3306/mydb?user=root&...
攻击者可以通过这些信息:
- 推断系统架构:了解你使用的框架、数据库类型、第三方库版本
- 发现潜在漏洞:某些库的特定版本存在已知安全漏洞
- 进行定向攻击:了解代码结构后,可以更有针对性地进行SQL注入、路径遍历等攻击
第三,用户体验的一致性很重要。如果404页面设计精美,而500页面却是一堆技术术语,会给用户造成困惑和不专业的感觉。统一的错误处理体验是产品成熟度的重要体现。
最后,监控和排查需要。合理的错误页面应该记录足够的日志信息供开发人员排查,同时又不向用户暴露敏感信息。这需要我们在友好性和可调试性之间找到平衡。
注意:根据OWASP(开放式Web应用程序安全项目)的建议,生产环境的应用应该关闭调试模式,对所有错误进行统一处理,避免向用户暴露任何系统内部信息。
下面这个表格对比了不同HTTP状态码的常见原因和处理建议:
| 状态码 | 类别 | 常见原因 | 用户提示建议 | 是否需要记录详细日志 |
|---|---|---|---|---|
| 400 | 客户端错误 | 请求参数格式错误、必填字段缺失 | "请求格式不正确,请检查后重试" | 是,记录请求参数 |
| 401 | 客户端错误 | 未认证或认证过期 | "请先登录"或"会话已过期,请重新登录" | 是,记录用户标识 |
| 403 | 客户端错误 | 权限不足 | "抱歉,您没有权限访问此资源" | 是,记录用户和资源信息 |
| 404 | 客户端错误 | 资源不存在 | "您访问的页面不存在" | 否,除非频繁出现 |
| 405 | 客户端错误 | 不支持的HTTP方法 | "不支持该请求方法" | 是,记录方法和端点 |
| 500 | 服务器错误 | 未捕获的异常、空指针等 | "服务器内部错误,请稍后重试" | 是,必须详细记录 |
| 502 | 服务器错误 | 上游服务不可用 | "服务暂时不可用,请稍后重试" | 是,记录依赖服务状态 |
| 503 | 服务器错误 | 服务过载或维护中 | "系统繁忙,请稍后重试"或"系统维护中" | 是,记录系统负载 |
从表格可以看出,500错误是唯一一个必须详细记录日志但绝对不能向用户展示细节的状态码。这种矛盾的处理要求,正是我们需要重点解决的问题。
2. 传统Tomcat应用的错误页面配置
对于传统的WAR包部署到独立Tomcat的场景,我们需要在web.xml中进行配置。这种方式虽然看起来有些"古老",但在很多传统企业应用中仍然广泛使用,理解其原理对排查历史遗留问题很有帮助。
2.1 基础配置:web.xml中的error-page
在Tomcat的web.xml中,我们可以通过<error-page>元素来配置错误页面。这个配置分为两种类型:按错误代码配置和按异常类型配置。
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
version="3.1">
<!-- 按HTTP状态码配置错误页面 -->
<error-page>
<error-code>404</error-code>
<location>/error/404.html</location>
</error-page>
<error-page>
<error-code>500</error-code>
<location>/error/500.html</location>
</error-page>
<error-page>
<error-code>403</error-code>
<location>/error/403.html</location>
</error-page>
<!-- 按异常类型配置错误页面 -->
<error-page>
<exception-type>java.lang.Throwable</exception-type>
<location>/error/general.html</location>
</error-page>
<!-- 更细粒度的异常类型配置 -->
<error-page>
<exception-type>java.sql.SQLException</exception-type>
<location>/error/database.html</location>
</error-page>
<error-page>
<exception-type>javax.servlet.ServletException</exception-type>
<location>/error/servlet.html</location>
</error-page>
</web-app>
这种配置方式有几个关键点需要注意:
-
优先级问题:Tomcat会按照
<error-page>声明的顺序进行匹配,但更具体的匹配会覆盖更通用的匹配。比如同时配置了<error-code>500</error-code>和<exception-type>java.lang.Throwable</exception-type>,当发生500错误时,会优先使用专门为500配置的页面。 -
路径问题:
<location>的值可以是相对路径或绝对路径。如果是相对路径,它相对于当前Web应用的上下文路径。我建议使用绝对路径(以/开头),这样更清晰。 -
静态与动态页面:你可以指向静态HTML页面,也可以指向JSP、Servlet等动态资源。对于需要显示动态信息的错误页面(比如错误ID),需要使用动态资源。
2.2 高级技巧:使用JSP动态错误页面
静态HTML页面虽然简单,但功能有限。在实际项目中,我更喜欢使用JSP作为错误页面,这样可以显示一些有用的信息(比如错误ID),方便用户反馈和问题追踪。
<%-- /WEB-INF/jsp/error/500.jsp --%>
<%@ page contentType="text/html;charset=UTF-8" language="java"
isErrorPage="true" %>
<%@ page import="java.util.UUID" %>
<%
// 生成唯一的错误ID,用于日志追踪
String errorId = UUID.randomUUID().toString().substring(0, 8);
// 记录错误日志,但不暴露给用户
String requestUri = (String) request.getAttribute("javax.servlet.error.request_uri");
Integer statusCode = (Integer) request.getAttribute("javax.servlet.error.status_code");
String servletName = (String) request.getAttribute("javax.servlet.error.servlet_name");
Throwable exception = (Throwable) request.getAttribute("javax.servlet.error.exception");
// 在实际项目中,这里应该使用日志框架记录
System.err.println("[" + errorId + "] Error processing request: " + requestUri);
if (exception != null) {
exception.printStackTrace();
}
%>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>服务器内部错误</title>
<style>
.error-container {
max-width: 800px;
margin: 50px auto;
padding: 30px;
background-color: #f8f9fa;
border-radius: 8px;
box-shadow: 0 2px 10px rgba(0,0,0,0.1);
}
.error-code {
font-size: 48px;
color: #dc3545;
margin-bottom: 20px;
}
.error-id {
background-color: #e9ecef;
padding: 10px;
border-radius: 4px;
font-family: monospace;
margin: 20px 0;
}
.actions {
margin-top: 30px;
}
.btn {
display: inline-block;
padding: 10px 20px;
background-color: #007bff;
color: white;
text-decoration: none;
border-radius: 4px;
margin-right: 10px;
}
</style>
</head>
<body>
<div class="error-container">
<div class="error-code">500</div>
<h1>抱歉,服务器内部错误</h1>
<p>我们遇到了一个意外错误,我们的技术团队已经收到通知并正在处理。</p>
<div class="error-id">
<strong>错误ID:</strong> <%= errorId %>
</div>
<p>如果您需要技术支持,请提供上面的错误ID,这将帮助我们更快定位问题。</p>
<div class="actions">
<a href="/" class="btn">返回首页</a>
<a href="javascript:history.back()" class="btn" style="background-color: #6c757d;">返回上一页</a>
<a href="mailto:support@example.com" class="btn" style="background-color: #28a745;">联系支持</a>
</div>
<div style="margin-top: 30px; font-size: 14px; color: #6c757d;">
<p>提示:</p>
<ul>
<li>请检查您输入的信息是否正确</li>
<li>尝试刷新页面或稍后重试</li>
<li>如果问题持续存在,请联系我们的技术支持团队</li>
</ul>
</div>
</div>
</body>
</html>
这个JSP页面有几个设计亮点:
isErrorPage="true":这个指令告诉容器这是一个错误页面,可以访问exception隐式对象。- 错误ID生成:为每个错误生成唯一ID,方便用户反馈和日志追踪。
- 友好的用户界面:清晰的错误说明、实用的操作按钮、友好的提示信息。
- 安全的信息处理:只在服务器端记录详细错误,不向用户暴露任何技术细节。
对应的web.xml配置需要更新:
<error-page>
<error-code>500</error-code>
<location>/WEB-INF/jsp/error/500.jsp</location>
</error-page>
<error-page>
<exception-type>java.lang.Throwable</exception-type>
<location>/WEB-INF/jsp/error/general.jsp</location>
</error-page>
提示:将错误页面放在
/WEB-INF/目录下可以防止用户直接访问,增加安全性。
2.3 常见陷阱与最佳实践
在实际配置Tomcat错误页面时,我遇到过不少坑,这里分享几个重要的注意事项:
陷阱1:路径配置错误
<!-- 错误示例:缺少开头的斜杠 -->
<error-page>
<error-code>500</error-code>
<location>error/500.html</location> <!-- 可能找不到页面 -->
</error-page>
<!-- 正确示例 -->
<error-page>
<error-code>500</error-code>
<location>/error/500.html</location> <!-- 绝对路径 -->
</error-page>
陷阱2:循环重定向 如果错误页面本身又抛出错误,会导致无限重定向。Tomcat有保护机制,但最好确保错误页面本身足够简单稳定。
陷阱3:忽略AJAX请求 现代Web应用大量使用AJAX,错误页面配置对AJAX请求可能不生效。需要额外处理:
// 前端统一错误处理
$.ajax({
url: '/api/data',
error: function(xhr, status, error) {
if (xhr.status === 500) {
// 显示友好的错误提示,而不是跳转页面
showErrorModal('服务器内部错误,请稍后重试');
}
}
});
最佳实践总结:
- 分类处理:不要只配置404,要为4xx和5xx分别配置
- 动态页面:使用JSP或Servlet生成错误页面,包含错误ID便于追踪
- 安全第一:绝对不要向用户显示堆栈信息
- 日志记录:在错误页面中记录详细日志,但只向用户显示友好信息
- 测试验证:定期测试各种错误场景,确保配置生效
3. Spring Boot的统一异常处理机制
Spring Boot提供了更现代、更灵活的异常处理方式。与Tomcat的web.xml配置相比,Spring Boot的方式更加类型安全,也更容易与业务逻辑集成。
3.1 使用@ControllerAdvice进行全局异常处理
@ControllerAdvice是Spring 3.2引入的注解,它可以定义全局的异常处理、数据绑定和数据预处理。这是我最推荐的Spring Boot异常处理方式。
package com.example.demo.exception;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.servlet.NoHandlerFoundException;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.UUID;
@ControllerAdvice
public class GlobalExceptionHandler {
private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);
/**
* 处理所有未捕获的异常
*/
@ExceptionHandler(Exception.class)
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
public String handleAllExceptions(Exception ex, HttpServletRequest request, Model model) {
String errorId = generateErrorId();
// 记录错误日志
logger.error("[ErrorID: {}] 未处理异常 - URI: {}, Method: {}",
errorId, request.getRequestURI(), request.getMethod(), ex);
// 将必要信息添加到模型
model.addAttribute("errorId", errorId);
model.addAttribute("timestamp", new Date());
model.addAttribute("path", request.getRequestURI());
model.addAttribute("message", "服务器内部错误,请稍后重试");
// 返回错误页面视图
return "error/500";
}
/**
* 处理404错误
*/
@ExceptionHandler(NoHandlerFoundException.class)
@ResponseStatus(HttpStatus.NOT_FOUND)
public String handleNotFound(NoHandlerFoundException ex, HttpServletRequest request, Model model) {
String errorId = generateErrorId();
logger.warn("[ErrorID: {}] 资源未找到 - URI: {}",
errorId, request.getRequestURI());
model.addAttribute("errorId", errorId);
model.addAttribute("timestamp", new Date());
model.addAttribute("path", request.getRequestURI());
model.addAttribute("message", "您访问的页面不存在");
return "error/404";
}
/**
* 处理业务异常
*/
@ExceptionHandler(BusinessException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
public String handleBusinessException(BusinessException ex,
HttpServletRequest request,
Model model) {
String errorId = generateErrorId();
logger.warn("[ErrorID: {}] 业务异常 - URI: {}, 错误码: {}, 消息: {}",
errorId, request.getRequestURI(), ex.getCode(), ex.getMessage());
model.addAttribute("errorId", errorId);
model.addAttribute("timestamp", new Date());
model.addAttribute("path", request.getRequestURI());
model.addAttribute("code", ex.getCode());
model.addAttribute("message", ex.getMessage());
return "error/business";
}
/**
* 处理数据库异常
*/
@ExceptionHandler({SQLException.class, DataAccessException.class})
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
public String handleDatabaseException(Exception ex,
HttpServletRequest request,
Model model) {
String errorId = generateErrorId();
// 记录详细错误,但只向用户显示通用信息
logger.error("[ErrorID: {}] 数据库异常 - URI: {}",
errorId, request.getRequestURI(), ex);
model.addAttribute("errorId", errorId);
model.addAttribute("timestamp", new Date());
model.addAttribute("path", request.getRequestURI());
model.addAttribute("message", "数据库操作失败,请稍后重试");
// 可以在这里添加监控告警
sendAlertToMonitoringSystem(errorId, "数据库异常", ex);
return "error/database";
}
/**
* 处理参数验证异常
*/
@ExceptionHandler(MethodArgumentNotValidException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
public String handleValidationException(MethodArgumentNotValidException ex,
HttpServletRequest request,
Model model) {
String errorId = generateErrorId();
// 提取验证错误信息
List<String> errors = ex.getBindingResult()
.getFieldErrors()
.stream()
.map(error -> error.getField() + ": " + error.getDefaultMessage())
.collect(Collectors.toList());
logger.warn("[ErrorID: {}] 参数验证失败 - URI: {}, 错误: {}",
errorId, request.getRequestURI(), errors);
model.addAttribute("errorId", errorId);
model.addAttribute("timestamp", new Date());
model.addAttribute("path", request.getRequestURI());
model.addAttribute("message", "请求参数验证失败");
model.addAttribute("errors", errors);
return "error/validation";
}
private String generateErrorId() {
return UUID.randomUUID().toString().substring(0, 8).toUpperCase();
}
private void sendAlertToMonitoringSystem(String errorId, String type, Exception ex) {
// 实际项目中这里应该集成监控系统
// 如发送到ELK、Prometheus、企业微信/钉钉等
logger.info("发送告警到监控系统 - ErrorID: {}, Type: {}", errorId, type);
}
}
这个全局异常处理器有几个关键特性:
- 分层处理:针对不同类型的异常提供不同的处理逻辑
- 错误ID:为每个错误生成唯一标识,便于追踪
- 详细日志:记录足够的信息供排查,但不暴露给用户
- 监控集成:可以方便地集成监控告警系统
3.2 自定义错误属性配置
Spring Boot允许我们通过ErrorAttributes接口自定义错误响应中的属性。这对于API接口特别有用,可以统一错误响应的格式。
package com.example.demo.config;
import org.springframework.boot.web.error.ErrorAttributeOptions;
import org.springframework.boot.web.servlet.error.DefaultErrorAttributes;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.WebRequest;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
@Component
public class CustomErrorAttributes extends DefaultErrorAttributes {
@Override
public Map<String, Object> getErrorAttributes(WebRequest webRequest,
ErrorAttributeOptions options) {
Map<String, Object> errorAttributes = super.getErrorAttributes(webRequest, options);
// 移除敏感信息
errorAttributes.remove("trace");
errorAttributes.remove("path");
// 添加自定义信息
String errorId = UUID.randomUUID().toString().substring(0, 8);
errorAttributes.put("errorId", errorId);
errorAttributes.put("timestamp", System.currentTimeMillis());
// 根据环境决定是否显示详细信息
boolean isProduction = "prod".equals(System.getProperty("spring.profiles.active"));
if (!isProduction && options.isIncluded(ErrorAttributeOptions.Include.STACK_TRACE)) {
// 非生产环境可以保留部分堆栈信息
errorAttributes.put("hint", "开发环境提示:检查日志获取更多信息");
} else {
// 生产环境只显示友好信息
errorAttributes.put("message", "系统繁忙,请稍后重试");
}
return errorAttributes;
}
}
然后,我们可以创建一个专门的错误控制器来处理错误页面:
package com.example.demo.controller;
import org.springframework.boot.web.servlet.error.ErrorController;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.servlet.RequestDispatcher;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.UUID;
@Controller
public class CustomErrorController implements ErrorController {
@RequestMapping("/error")
public String handleError(HttpServletRequest request, Model model) {
Object status = request.getAttribute(RequestDispatcher.ERROR_STATUS_CODE);
Object exception = request.getAttribute(RequestDispatcher.ERROR_EXCEPTION);
Object message = request.getAttribute(RequestDispatcher.ERROR_MESSAGE);
String errorId = UUID.randomUUID().toString().substring(0, 8);
String path = (String) request.getAttribute(RequestDispatcher.ERROR_REQUEST_URI);
model.addAttribute("errorId", errorId);
model.addAttribute("timestamp", new Date());
model.addAttribute("path", path);
if (status != null) {
int statusCode = Integer.parseInt(status.toString());
model.addAttribute("status", statusCode);
if (statusCode == HttpStatus.NOT_FOUND.value()) {
model.addAttribute("message", "页面未找到");
return "error/404";
} else if (statusCode == HttpStatus.FORBIDDEN.value()) {
model.addAttribute("message", "访问被拒绝");
return "error/403";
} else if (statusCode == HttpStatus.INTERNAL_SERVER_ERROR.value()) {
model.addAttribute("message", "服务器内部错误");
// 记录详细错误日志
if (exception instanceof Exception) {
logger.error("[ErrorID: {}] 服务器错误 - Path: {}",
errorId, path, (Exception) exception);
}
return "error/500";
}
}
model.addAttribute("message", "发生未知错误");
return "error/general";
}
// Spring Boot 2.3+ 需要重写此方法
public String getErrorPath() {
return "/error";
}
}
3.3 针对REST API的异常处理
对于前后端分离的项目,我们需要返回JSON格式的错误响应,而不是HTML页面。Spring Boot可以很容易地实现这一点。
package com.example.demo.controller;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
@RestControllerAdvice
public class RestApiExceptionHandler {
/**
* 处理所有未捕获异常,返回JSON格式错误响应
*/
@ExceptionHandler(Exception.class)
public ResponseEntity<Map<String, Object>> handleAllExceptions(
Exception ex, HttpServletRequest request) {
String errorId = UUID.randomUUID().toString().substring(0, 8);
logger.error("[ErrorID: {}] REST API异常 - URI: {}, Method: {}",
errorId, request.getRequestURI(), request.getMethod(), ex);
Map<String, Object> errorResponse = new HashMap<>();
errorResponse.put("success", false);
errorResponse.put("errorId", errorId);
errorResponse.put("timestamp", new Date());
errorResponse.put("path", request.getRequestURI());
errorResponse.put("message", "服务器内部错误,请稍后重试");
// 开发环境可以包含更多信息
if (!isProduction()) {
errorResponse.put("exception", ex.getClass().getName());
errorResponse.put("detail", ex.getMessage());
}
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
.body(errorResponse);
}
/**
* 处理业务异常
*/
@ExceptionHandler(BusinessException.class)
public ResponseEntity<Map<String, Object>> handleBusinessException(
BusinessException ex, HttpServletRequest request) {
String errorId = UUID.randomUUID().toString().substring(0, 8);
logger.warn("[ErrorID: {}] 业务异常 - URI: {}, Code: {}",
errorId, request.getRequestURI(), ex.getCode());
Map<String, Object> errorResponse = new HashMap<>();
errorResponse.put("success", false);
errorResponse.put("errorId", errorId);
errorResponse.put("timestamp", new Date());
errorResponse.put("code", ex.getCode());
errorResponse.put("message", ex.getMessage());
errorResponse.put("path", request.getRequestURI());
return ResponseEntity.status(HttpStatus.BAD_REQUEST)
.body(errorResponse);
}
/**
* 处理参数验证异常
*/
@ExceptionHandler(MethodArgumentNotValidException.class)
public ResponseEntity<Map<String, Object>> handleValidationException(
MethodArgumentNotValidException ex, HttpServletRequest request) {
String errorId = UUID.randomUUID().toString().substring(0, 8);
Map<String, Object> errorResponse = new HashMap<>();
errorResponse.put("success", false);
errorResponse.put("errorId", errorId);
errorResponse.put("timestamp", new Date());
errorResponse.put("path", request.getRequestURI());
errorResponse.put("message", "参数验证失败");
// 收集所有字段错误
Map<String, String> fieldErrors = new HashMap<>();
ex.getBindingResult().getFieldErrors().forEach(error -> {
fieldErrors.put(error.getField(), error.getDefaultMessage());
});
errorResponse.put("errors", fieldErrors);
return ResponseEntity.status(HttpStatus.BAD_REQUEST)
.body(errorResponse);
}
private boolean isProduction() {
return "prod".equals(System.getProperty("spring.profiles.active"));
}
}
对于REST API,我们还需要统一响应格式。这里是一个通用的API响应封装类:
package com.example.demo.dto;
import com.fasterxml.jackson.annotation.JsonInclude;
import java.util.Date;
@JsonInclude(JsonInclude.Include.NON_NULL)
public class ApiResponse<T> {
private boolean success;
private String errorId;
private Date timestamp;
private String message;
private T data;
private String code;
// 成功响应
public static <T> ApiResponse<T> success(T data) {
ApiResponse<T> response = new ApiResponse<>();
response.setSuccess(true);
response.setTimestamp(new Date());
response.setData(data);
return response;
}
// 失败响应
public static <T> ApiResponse<T> error(String message, String errorId) {
ApiResponse<T> response = new ApiResponse<>();
response.setSuccess(false);
response.setTimestamp(new Date());
response.setMessage(message);
response.setErrorId(errorId);
return response;
}
public static <T> ApiResponse<T> error(String message, String errorId, String code) {
ApiResponse<T> response = error(message, errorId);
response.setCode(code);
return response;
}
// getters and setters
// ...
}
4. 高级场景与安全加固
在实际生产环境中,仅仅配置错误页面是不够的。我们还需要考虑更多高级场景和安全加固措施。
4.1 防止信息泄露的完整方案
信息泄露是Web应用安全的重要威胁。除了错误页面,我们还需要从多个层面进行防护。
1. 关闭调试模式 Spring Boot应用在生产环境必须关闭调试模式:
# application-prod.properties
server.error.include-exception=false
server.error.include-stacktrace=never
server.error.include-message=never
server.error.include-binding-errors=never
# 关闭Spring Boot的Whitelabel错误页面
server.error.whitelabel.enabled=false
# 自定义错误路径
server.error.path=/error
2. 自定义错误页面路径 将错误页面放在安全的位置,避免直接访问:
package com.example.demo.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
// 保护错误页面目录,禁止直接访问
registry.addResourceHandler("/error-pages/**")
.addResourceLocations("classpath:/templates/error-pages/")
.setCachePeriod(3600)
.resourceChain(true);
}
}
3. 敏感信息过滤 在日志中过滤敏感信息,防止日志泄露:
package com.example.demo.filter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
@Component
public class SensitiveDataFilter implements Filter {
private static final Logger logger = LoggerFactory.getLogger(SensitiveDataFilter.class);
private static final List<String> SENSITIVE_PARAMS = Arrays.asList(
"password", "passwd", "pwd", "secret", "token",
"creditcard", "ccnumber", "ssn", "socialsecurity"
);
@Override
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
HttpServletRequest httpRequest = (HttpServletRequest) request;
SensitiveRequestWrapper wrappedRequest = new SensitiveRequestWrapper(httpRequest);
// 记录请求日志,但过滤敏感参数
if (logger.isDebugEnabled()) {
logger.debug("请求: {} {}, 参数: {}",
httpRequest.getMethod(),
httpRequest.getRequestURI(),
filterSensitiveParams(wrappedRequest.getParameterMap()));
}
chain.doFilter(wrappedRequest, response);
}
private String filterSensitiveParams(Map<String, String[]> params) {
Map<String, String[]> filtered = new HashMap<>(params);
for (String key : params.keySet()) {
if (isSensitive(key)) {
filtered.put(key, new String[]{"[FILTERED]"});
}
}
return filtered.toString();
}
private boolean isSensitive(String paramName) {
String lowerName = paramName.toLowerCase();
return SENSITIVE_PARAMS.stream().anyMatch(lowerName::contains);
}
// 其他方法...
}
4. 安全响应头配置 添加安全相关的HTTP响应头:
package com.example.demo.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
// 其他安全配置...
.headers()
.contentSecurityPolicy("default-src 'self'; script-src 'self' 'unsafe-inline'")
.and()
.httpStrictTransportSecurity()
.includeSubDomains(true)
.maxAgeInSeconds(31536000)
.and()
.frameOptions().deny()
.xssProtection().block(true)
.and()
// 错误处理配置
.exceptionHandling()
.accessDeniedPage("/error/403")
.authenticationEntryPoint(new HttpStatusEntryPoint(HttpStatus.UNAUTHORIZED));
}
}
4.2 监控与告警集成
完善的错误处理应该包含监控和告警机制。这里我分享一个与Prometheus和Grafana集成的方案。
1. 错误指标收集
package com.example.demo.monitor;
import io.micrometer.core.instrument.Counter;
import io.micrometer.core.instrument.MeterRegistry;
import org.springframework.stereotype.Component;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
@Component
public class ErrorMetrics {
private final MeterRegistry registry;
private final ConcurrentMap<String, Counter> errorCounters;
public ErrorMetrics(MeterRegistry registry) {
this.registry = registry;
this.errorCounters = new ConcurrentHashMap<>();
}
public void recordError(String errorType, String path, String method) {
String key = String.format("%s.%s.%s", errorType, path, method);
Counter counter = errorCounters.computeIfAbsent(key, k ->
Counter.builder("application.errors")
.tag("type", errorType)
.tag("path", path)
.tag("method", method)
.description("应用错误计数")
.register(registry)
);
counter.increment();
}
public void recordHttpError(int statusCode, String path, String method) {
recordError("http." + statusCode, path, method);
}
public void recordException(Class<?> exceptionClass, String path, String method) {
recordError("exception." + exceptionClass.getSimpleName(), path, method);
}
}
2. 集成到异常处理器
@ExceptionHandler(Exception.class)
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
public String handleAllExceptions(Exception ex, HttpServletRequest request,
Model model, ErrorMetrics errorMetrics) {
String errorId = generateErrorId();
// 记录指标
errorMetrics.recordException(ex.getClass(),
request.getRequestURI(),
request.getMethod());
// 发送告警(根据错误频率决定)
if (shouldSendAlert(ex)) {
sendAlert(ex, errorId, request);
}
// 记录详细日志
logger.error("[ErrorID: {}] 未处理异常 - URI: {}", errorId, request.getRequestURI(), ex);
// 返回用户友好的错误页面
model.addAttribute("errorId", errorId);
model.addAttribute("message", "系统繁忙,请稍后重试");
return "error/500";
}
private boolean shouldSendAlert(Exception ex) {
// 根据错误类型、频率等逻辑决定是否发送告警
// 例如:数据库连接错误立即告警,业务逻辑错误可以延迟或聚合
return ex instanceof SQLException ||
ex instanceof IOException ||
ex instanceof TimeoutException;
}
private void sendAlert(Exception ex, String errorId, HttpServletRequest request) {
// 集成企业微信、钉钉、Slack等告警
String alertMessage = String.format(
"🚨 系统异常告警\n" +
"错误ID: %s\n" +
"异常类型: %s\n" +
"请求路径: %s\n" +
"时间: %s\n" +
"请及时处理!",
errorId, ex.getClass().getSimpleName(),
request.getRequestURI(), new Date()
);
// 调用告警服务
alertService.send(alertMessage);
}
3. Prometheus配置示例
# prometheus.yml
scrape_configs:
- job_name: 'spring-boot-app'
metrics_path: '/actuator/prometheus'
static_configs:
- targets: ['localhost:8080']
relabel_configs:
- source_labels: [__address__]
target_label: instance
regex: '(.*):.*'
replacement: '${1}'
# 告警规则
groups:
- name: application_errors
rules:
- alert: HighErrorRate
expr: rate(application_errors_total[5m]) > 10
for: 2m
labels:
severity: warning
annotations:
summary: "应用错误率过高"
description: "过去5分钟内错误率超过10次/分钟,当前值: {{ $value }}"
4.3 性能优化与缓存策略
错误页面虽然不常出现,但一旦出现往往是在高并发或系统压力大的时候。因此,错误页面的性能优化也很重要。
1. 静态资源缓存
@Configuration
public class CacheConfig {
@Bean
public WebServerFactoryCustomizer<ConfigurableServletWebServerFactory> webServerFactoryCustomizer() {
return factory -> {
// 配置错误页面的缓存策略
factory.addErrorPages(new ErrorPage(HttpStatus.NOT_FOUND, "/error/404"));
factory.addErrorPages(new ErrorPage(HttpStatus.INTERNAL_SERVER_ERROR, "/error/500"));
// 添加静态资源处理器
factory.addInitializers(servletContext -> {
ServletRegistration.Dynamic registration =
servletContext.addServlet("errorServlet", new ErrorServlet());
registration.addMapping("/error/*");
registration.setInitParameter("cacheControl", "max-age=3600, public");
});
};
}
}
// 自定义错误Servlet,支持缓存
public class ErrorServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
// 设置缓存头
resp.setHeader("Cache-Control", "max-age=3600, public");
resp.setHeader("ETag", "\"error-page-v1\"");
// 检查If-None-Match
String ifNoneMatch = req.getHeader("If-None-Match");
if ("\"error-page-v1\"".equals(ifNoneMatch)) {
resp.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
return;
}
// 返回错误页面内容
String errorCode = getErrorCode(req);
String html = generateErrorHtml(errorCode);
resp.setContentType("text/html;charset=UTF-8");
resp.getWriter().write(html);
}
// 其他方法...
}
2. CDN缓存策略 对于静态错误页面,可以考虑使用CDN:
# nginx配置示例
server {
listen 80;
server_name example.com;
location /error/ {
# 错误页面缓存1小时
expires 1h;
add_header Cache-Control "public, max-age=3600";
# 防止代理缓存动态内容
proxy_no_cache 1;
proxy_cache_bypass 1;
proxy_pass http://backend:8080;
}
error_page 404 /error/404.html;
error_page 500 502 503 504 /error/50x.html;
location = /error/404.html {
internal;
root /usr/share/nginx/html;
expires 1h;
}
location = /error/50x.html {
internal;
root /usr/share/nginx/html;
expires 1h;
}
}
3. 降级策略 当错误处理系统本身出现问题时,需要有降级方案:
@Component
public class FallbackErrorHandler {
private static final String SIMPLE_500_HTML = """
<!DOCTYPE html>
<html>
<head>
<title>系统繁忙</title>
<meta charset="UTF-8">
<style>
body { font-family: Arial, sans-serif; text-align: center; padding: 50px; }
h1 { color: #d9534f; }
</style>
</head>
<body>
<h1>500</h1>
<p>系统繁忙,请稍后重试</p>
<p>错误ID: %s</p>
</body>
</html>
""";
public String getFallbackErrorPage(String errorId) {
return String.format(SIMPLE_500_HTML, errorId);
}
public String getFallbackJsonError(String errorId) {
return String.format(
"{\"success\":false,\"errorId\":\"%s\",\"message\":\"系统繁忙\"}",
errorId
);
}
}
5. 实战:构建企业级错误处理系统
在实际企业应用中,我们需要一个完整的错误处理系统,而不仅仅是几个错误页面。下面我分享一个在实际项目中验证过的完整方案。
5.1 错误分类与处理策略
首先,我们需要对错误进行分类,不同类别的错误采用不同的处理策略:
package com.example.demo.error;
public enum ErrorCategory {
// 客户端错误(4xx)
CLIENT_ERROR(1, "客户端错误", AlertLevel.LOW),
VALIDATION_ERROR(2, "参数验证错误", AlertLevel.LOW),
AUTH_ERROR(3, "认证授权错误", AlertLevel.MEDIUM),
// 服务器错误(5xx)
SERVER_ERROR(10, "服务器内部错误", AlertLevel.HIGH),
DATABASE_ERROR(11, "数据库错误", AlertLevel.HIGH),
EXTERNAL_SERVICE_ERROR(12, "外部服务错误", AlertLevel.HIGH),
TIMEOUT_ERROR(13, "超时错误", AlertLevel.MEDIUM),
// 业务错误
BUSINESS_ERROR(20, "业务逻辑错误", AlertLevel.MEDIUM),
INTEGRATION_ERROR(21, "集成错误", AlertLevel.HIGH);
private final int code;
private final String description;
private final AlertLevel alertLevel;
ErrorCategory(int code, String description, AlertLevel alertLevel) {
this.code = code;
this.description = description;
this.alertLevel = alertLevel;
}
// getters...
}
public enum AlertLevel {
LOW(1), // 仅记录日志
MEDIUM(2), // 记录日志并发送到监控系统
HIGH(3); // 立即告警
private final int priority;
AlertLevel(int priority) {
this.priority = priority;
}
public boolean shouldAlert() {
return this.priority >= MEDIUM.priority;
}
}
5.2 统一错误响应格式
定义统一的错误响应格式,便于前端处理:
package com.example.demo.dto;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonInclude;
import java.time.LocalDateTime;
@JsonInclude(JsonInclude.Include.NON_NULL)
public class ErrorResponse {
private boolean success;
private String errorId;
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private LocalDateTime timestamp;
private String message;
private String userMessage; // 给用户看的友好消息
private String developerMessage; // 给开发者看的详细消息(仅开发环境)
private String path;
private Integer status;
private String errorCode;
private Map<String, Object> details;
// 静态工厂方法
public static ErrorResponse of(String errorId, String message) {
ErrorResponse response = new ErrorResponse();
response.setSuccess(false);
response.setErrorId(errorId);
response.setTimestamp(LocalDateTime.now());
response.setMessage(message);
return response;
}
public static ErrorResponse of(String errorId, String message,
String path, Integer status) {
ErrorResponse response = of(errorId, message);
response.setPath(path);
response.setStatus(status);
return response;
}
// 链式调用方法
public ErrorResponse withUserMessage(String userMessage) {
this.userMessage = userMessage;
return this;
}
public ErrorResponse withDeveloperMessage(String developerMessage) {
this.developerMessage = developerMessage;
return this;
}
public ErrorResponse withErrorCode(String errorCode) {
this.errorCode = errorCode;
return this;
}
public ErrorResponse withDetail(String key, Object value) {
if (this.details == null) {
this.details = new HashMap<>();
}
this.details.put(key, value);
return this;
}
// getters and setters...
}
5.3 完整的异常处理框架
结合以上组件,构建完整的异常处理框架:
package com.example.demo.exception;
import com.example.demo.dto.ErrorResponse;
import com.example.demo.error.ErrorCategory;
import com.example.demo.monitor.ErrorMetrics;
import com.example.demo.service.AlertService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.context.request.ServletWebRequest;
import org.springframework.web.context.request.WebRequest;
import javax.servlet.http.HttpServletRequest;
import java.util.UUID;
@RestControllerAdvice
public class GlobalExceptionHandler {
private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);
@Autowired
private ErrorMetrics errorMetrics;
@Autowired
private AlertService alertService;
@Value("${app.env:dev}")
private String environment;
@ExceptionHandler(Exception.class)
public ResponseEntity<ErrorResponse> handleUncaughtException(
Exception ex, WebRequest request) {
String errorId = generateErrorId();
HttpServletRequest httpRequest = ((ServletWebRequest) request).getRequest();
// 记录错误指标
errorMetrics.recordException(ex.getClass(),
httpRequest.getRequestURI(),
httpRequest.getMethod());
// 构建错误响应
ErrorResponse errorResponse = ErrorResponse.of(errorId, "系统内部错误")
.withUserMessage("系统繁忙,请稍后重试")
.withErrorCode("INTERNAL_ERROR")
.withDetail("path", httpRequest.getRequestURI())
.withDetail("method", httpRequest.getMethod());
// 开发环境包含更多信息
if ("dev".equals(environment) || "test".equals(environment)) {
errorResponse.withDeveloperMessage(ex.getMessage())
.withDetail("exception", ex.getClass().getName())
.withDetail("stackTrace", getStackTrace(ex));
}
// 记录详细日志
logger.error("[ErrorID: {}] 未捕获异常 - {} {}",
errorId, httpRequest.getMethod(), httpRequest.getRequestURI(), ex);
// 发送告警(根据错误类型)
if (shouldAlert(ex)) {
alertService.sendErrorAlert(errorId, ex, httpRequest);
}
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
.body(errorResponse);
}
@ExceptionHandler(BusinessException.class)
public ResponseEntity<ErrorResponse> handleBusinessException(
BusinessException ex, WebRequest request) {
String errorId = generateErrorId();
HttpServletRequest httpRequest = ((ServletWebRequest) request).getRequest();
ErrorResponse errorResponse = ErrorResponse.of(errorId, ex.getMessage())
.withUserMessage(ex.getUserMessage())
.withErrorCode(ex.getErrorCode())
.withDetail("path", httpRequest.getRequestURI());
// 记录业务异常日志
logger.warn("[ErrorID: {}] 业务异常 - {}: {}",
errorId, ex.getErrorCode(), ex.getMessage());
return ResponseEntity.status(ex.getHttpStatus())
.body(errorResponse);
}
@ExceptionHandler(ValidationException.class)
public ResponseEntity<ErrorResponse> handleValidationException(
ValidationException ex, WebRequest request) {
String errorId = generateErrorId();
HttpServletRequest httpRequest = ((ServletWebRequest) request).getRequest();
ErrorResponse errorResponse = ErrorResponse.of(errorId, "参数验证失败")
.withUserMessage("请检查输入参数")
.withErrorCode("VALIDATION_ERROR")
.withDetail("path", httpRequest.getRequestURI())
.withDetail("violations", ex.getViolations());
logger.info("[ErrorID: {}] 参数验证失败 - {}", errorId, ex.getViolations());
return ResponseEntity.status(HttpStatus.BAD_REQUEST)
.body(errorResponse);
}
private String generateErrorId() {
return UUID.randomUUID().toString().substring(0, 8).toUpperCase();
}
private boolean shouldAlert(Exception ex) {
// 根据异常类型决定是否发送告警
return ex instanceof DatabaseException ||
ex instanceof ExternalServiceException ||
ex instanceof OutOfMemoryError;
}
private String getStackTrace(Exception ex) {
// 获取简化的堆栈信息(避免太长)
StackTraceElement[] stackTrace = ex.getStackTrace();
StringBuilder sb = new StringBuilder();
for (int i = 0; i < Math.min(stackTrace.length, 10); i++) {
sb.append(stackTrace[i]).append("\n");
}
if (stackTrace.length > 10) {
sb.append("... and ").append(stackTrace.length - 10).append(" more");
}
return sb.toString();
}
}
5.4 错误页面模板
最后,提供一套完整的错误页面模板:
<!DOCTYPE html>
<!-- error/500.html -->
<html lang="zh-CN" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>服务器错误 - 系统名称</title>
<link rel="stylesheet" href="/static/css/error.css">
<style>
.error-container {
max-width: 600px;
margin: 100px auto;
padding: 40px;
background: white;
border-radius: 10px;
box-shadow: 0 5px 20px rgba(0,0,0,0.1);
text-align: center;
}
.error-code {
font-size: 72px;
color: #dc3545;
margin-bottom: 20px;
font-weight: bold;
}
.error-title {
font-size: 24px;
color: #333;
margin-bottom: 20px;
}
.error-message {
color: #666;
margin-bottom: 30px;
line-height: 1.6;
}
.error-id {
background: #f8f9fa;
padding: 15px;
border-radius: 5px;
margin: 20px 0;
font-family: 'Courier New', monospace;
font-size: 14px;
word-break: break-all;
}
.actions {
display: flex;
gap: 15px;
justify-content: center;
margin-top: 30px;
}
.btn {
padding: 12px 24px;
border-radius: 5px;
text-decoration: none;
font-weight: 500;
transition: all 0.3s;
}
.btn-primary {
background: #007bff;
color: white;
}
.btn-secondary {
background: #6c757d;
color: white;
}
.btn:hover {
opacity: 0.9;
transform: translateY(-2px);
}
.contact-info {
margin-top: 30px;
padding-top: 20px;
border-top: 1px solid #eee;
color: #888;
font-size: 14px;
}
</style>
</head>
<body>
<div class="error-container">
<div class="error-code">500</div>
<h1 class="error-title">服务器内部错误</h1>
<div class="error-message">
<p>抱歉,服务器处理您的请求时出现了问题。</p>
<p>我们的技术团队已经收到通知,正在紧急处理中。</p>
</div>
<div class="error-id">
<strong>错误ID:</strong> <span th:text="${errorId}">ERROR123</span>
</div>
<p>如果您需要技术支持,请提供上面的错误ID,这将帮助我们更快定位问题。</p>
<div class="actions">
<a href="/" class="btn btn-primary">返回首页</a>
<a href="javascript:history.back()" class="btn btn-secondary">返回上一页</a>
<button onclick="copyErrorId()" class="btn" style="background: #28a745; color: white;">
复制错误ID
</button>
</div>
<div class="contact-info">
<p>技术支持:support@example.com | 电话:400-xxx-xxxx</p>
<p>工作时间:周一至周五 9:00-18:00</p>
</div>
</div>
<script>
function copyErrorId() {
const errorId = document.querySelector('.error-id span').textContent;
navigator.clipboard.writeText(errorId).then(() => {
alert('错误ID已复制到剪贴板');
});
}
// 自动重试逻辑(可选)
let retryCount = 0;
const maxRetries = 3;
function checkService() {
fetch('/health')
.then(response => {
if (response.ok) {
window.location.reload();
} else {
retry();
}
})
.catch(() => retry());
}
function retry() {
if (retryCount < maxRetries) {
retryCount++;
setTimeout(checkService, 5000 * retryCount); // 5s, 10s, 15s
}
}
// 可选:5分钟后自动检查服务是否恢复
setTimeout(checkService, 300000);
</script>
</body>
</html>
这套错误处理系统在实际项目中经过了验证,能够:
- 提供友好的用户界面:清晰的错误提示、有用的操作指引
- 确保信息安全:不泄露任何技术细节给用户
- 便于问题追踪:每个错误都有唯一ID,方便用户反馈和开发排查
- 集成监控告警:重要错误及时通知相关人员
- 支持多环境:开发环境显示更多信息,生产环境只显示友好信息
- 性能优化:错误页面有缓存,不影响系统性能
错误处理不是一次性任务,而是一个持续改进的过程。每次线上问题都是优化错误处理机制的机会。通过收集用户反馈、分析错误日志、优化错误提示,我们可以不断提升系统的稳定性和用户体验。
427



被折叠的 条评论
为什么被折叠?



