SpringBoot中默认异常处理机制的实现
作者:南姜先生
在 Spring Boot 中,为了简化 Web 应用的异常处理流程,它提供了一套默认的全局异常处理机制,其中最核心的就是 /error 接口。这个接口是 Spring Boot 提供的一个内置错误页面控制器(BasicErrorController),用于统一返回错误信息。
🧠 一句话总结:
✅ Spring Boot 默认使用 BasicErrorController 来处理所有未被捕获的异常,并通过 /error 接口返回结构化的错误响应或跳转到错误页面(如 HTML 页面)。
🔍 一、默认行为概览
| 请求类型 | 返回内容 |
|---|---|
| 浏览器请求(HTML) | 跳转到 /error 页面(如 error.html) |
| API 请求(JSON/REST) | 返回 JSON 格式的错误信息 |
例如:
- 访问一个不存在的路径:
GET /not-found - 控制器抛出未处理的异常 都会被 Spring Boot 的
/error端点捕获并处理。
🛠️ 二、核心组件解析
1.BasicErrorController
这是 Spring Boot 默认提供的错误处理器,负责处理 /error 请求。
@Controller
@RequestMapping("${server.error.path:${spring.mvc.async.request-timeout}}")
public class BasicErrorController extends AbstractErrorController {
...
}- 默认路径为
/error(可通过server.error.path配置修改) - 支持两种响应格式:
text/html:返回 HTML 错误页面(如error.html)- 其他格式(如 JSON):返回结构化错误信息
2.ErrorAttributes接口
该接口定义了错误信息的内容来源,包括:
- 异常对象
- HTTP 状态码
- 请求 URL
- 时间戳等
默认实现是 DefaultErrorAttributes,你也可以自定义。
3.ErrorViewResolver接口
用于解析 HTML 错误页面。例如:
/templates/error/404.html/templates/error/5xx.html/templates/error.html
Spring Boot 会根据状态码优先匹配具体页面。
📦 三、默认返回的 JSON 错误结构
当你访问一个 REST 接口时,如果发生异常且没有被 @ExceptionHandler 或 @ControllerAdvice 捕获,Spring Boot 会返回如下格式的 JSON 响应:
{
"timestamp": "2025-07-12T10:45:00.000+00:00",
"status": 404,
"error": "Not Found",
"path": "/not-found"
}字段说明:
| 字段名 | 含义 |
|---|---|
| timestamp | 错误发生时间 |
| status | HTTP 状态码 |
| error | 错误描述 |
| exception | 异常类名(仅当 spring.boot.debug=true 时显示) |
| message | 异常消息(可选) |
| path | 出错的请求路径 |
🌐 四、如何自定义错误处理?
虽然 Spring Boot 提供了默认的错误处理机制,但在实际项目中我们通常需要进行定制:
1.方式一:自定义ErrorAttributes
你可以实现 ErrorAttributes 接口来自定义错误信息内容:
@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.方式三:创建自定义错误页面(HTML)
将 HTML 页面放在以下位置之一即可:
src/main/resources/templates/error/404.htmlsrc/main/resources/static/error/500.htmlsrc/main/resources/public/error.html
Spring Boot 会根据 HTTP 状态码自动选择对应的页面。
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);
}
}这种方式比默认机制更灵活,适用于大型项目。
⚙️ 五、配置相关属性(application.yml)
你可以在 application.yml 或 application.properties 中配置一些与错误相关的参数:
spring:
mvc:
async:
request-timeout: 0 # 禁用超时控制
server:
error:
path: /my-error # 自定义错误路径
whitelabel:
enabled: false # 关闭默认白标错误页✅ 六、总结
| 项目 | 内容 |
|---|---|
| 默认错误端点 | /error |
| 默认控制器 | BasicErrorController |
| 默认错误信息 | DefaultErrorAttributes |
| 默认视图支持 | 支持 HTML 错误页面(按状态码命名) |
| JSON 输出格式 | 包含 timestamp, status, error, path 等字段 |
| 可扩展性 | 支持自定义 ErrorAttributes、ErrorController、HTML 页面、@ControllerAdvice |
到此这篇关于SpringBoot中默认异常处理机制的实现的文章就介绍到这了,更多相关SpringBoot 默认异常处理机制内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
