OpenAPI 3.0 中自定义异常响应需显式定义 schema 和 responses,Java 生态常用 Springdoc 实现:通过 @Schema 定义 ErrorResponse 类,@ApiResponse 或 @ApiResponses 在接口中绑定状态码与错误模型,并配合 @ControllerAdvice 统一异常处理及自动注册。

在 OpenAPI 3.0 中,自定义异常返回(如 ErrorResponse)不是靠“自动扫描”或框架魔法生成的,而是通过显式定义 schema 和 responses 来声明。Java 生态中常用 Springdoc(基于 Spring Boot + Swagger UI)实现,核心是:用 @Schema 注解定义错误模型,用 @ApiResponse 或全局 @ControllerAdvice 统一响应契约。
定义 ErrorResponse 类并标注 Schema
先创建一个标准错误响应类,用 @Schema 描述整体结构,并为每个字段添加语义说明:
@Schema(description = "通用错误响应结构")
public class ErrorResponse {
@Schema(description = "业务错误码,如 'VALIDATION_FAILED'", example = "BAD_REQUEST")
private String code;
<pre class='brush:java;toolbar:false;'>@Schema(description = "用户可读的错误消息", example = "用户名不能为空")
private String message;
@Schema(description = "错误发生的时间戳(ISO 8601 格式)", example = "2024-05-20T14:30:00Z")
private Instant timestamp;
@Schema(description = "可选的详细错误信息(调试用)", nullable = true)
private String details;
// 构造函数、getter/setter 省略}
在接口中声明异常响应
使用 @ApiResponse 显式绑定 HTTP 状态码与 ErrorResponse Schema:
立即学习“Java免费学习笔记(深入)”;
- 单个接口声明:在
@Operation下用@ApiResponse指定 4xx/5xx 响应体 - 推荐方式:配合
@ApiResponses批量声明常见错误(如 400、404、500) - 确保
content的schema引用到你定义的类
@Operation(summary = "根据ID获取用户")
@ApiResponses({
@ApiResponse(responseCode = "200", description = "成功返回用户"),
@ApiResponse(
responseCode = "404",
description = "用户不存在",
content = @Content(schema = @Schema(implementation = ErrorResponse.class))
),
@ApiResponse(
responseCode = "500",
description = "内部服务异常",
content = @Content(schema = @Schema(implementation = ErrorResponse.class))
)
})
@GetMapping("/users/{id}")
public User getUser(@PathVariable Long id) { ... }
统一异常处理 + OpenAPI 自动注册
Spring Boot 项目通常用 @ControllerAdvice 全局捕获异常并返回 ErrorResponse。为了让 Springdoc 自动识别这些全局响应,需配置:
- 在
@ControllerAdvice类上加@Schema注解(Springdoc 3.x+ 支持) - 或使用
springdoc.default-consumes-produces.media-type确保 JSON 媒体类型被识别 - 关键:在
application.yml中启用全局响应扫描(可选但推荐)
springdoc:
api-docs:
path: /v3/api-docs
swagger-ui:
path: /swagger-ui.html
# 启用对 @ControllerAdvice 中 @ApiResponse 的自动发现(Springdoc 2.2+)
enable-default-response: true
验证生成的 OpenAPI JSON/YAML
启动应用后访问 /v3/api-docs,检查输出中是否包含:
-
components.schemas.ErrorResponse定义(含字段、类型、示例) - 对应接口的
responses."404".content."application/json".schema.$ref指向#/components/schemas/ErrorResponse - 确保
details字段标记为"nullable": true(由@Schema(nullable = true)控制)


















