Spring Boot中ResponseStatusException对应的OpenAPI Schema类疑问
Spring Boot中ResponseStatusException对应的OpenAPI错误响应最优实现
核心结论
针对你的场景,最优实现方式分Spring Boot版本区别对待,是否需要自定义类也由此决定:
1. 如果你使用Spring Boot 3.x(Spring 6+)
Spring 6引入了符合RFC 7807规范的ProblemDetail类(org.springframework.http.ProblemDetail),这是官方提供的标准错误响应实体类。抛出ResponseStatusException时,框架默认会返回该类对应的JSON结构(若需兼容旧格式可通过配置调整,但推荐使用标准结构)。
此时在OpenAPI中直接引用即可,无需自定义类:
@ApiResponse(responseCode = "404", description = "Item not found", content = @Content(mediaType = MediaType.APPLICATION_JSON_VALUE, schema = @Schema(implementation = ProblemDetail.class)))
2. 如果你使用Spring Boot 2.x
Spring Boot 2.x官方没有提供对应示例中默认错误结构的公开实体类(框架通过DefaultErrorAttributes构建Map返回响应),因此最优方式是自定义一个匹配响应结构的DTO类:
步骤1:自定义错误响应DTO
public class DefaultErrorResponse { private String timestamp; private int status; private String error; private String exception; private String message; private String path; // 生成Getter、Setter方法 }
步骤2:在OpenAPI注解中引用
@ApiResponse(responseCode = "404", description = "Item not found", content = @Content(mediaType = MediaType.APPLICATION_JSON_VALUE, schema = @Schema(implementation = DefaultErrorResponse.class)))
关键注意事项
- 修正代码中的不一致:你抛出的是
HttpStatus.NOT_FOUND(404),但注解中写的responseCode = "400",需统一为"404",避免文档与实际行为不符。 - 若想统一全局错误响应格式,建议自定义全局异常处理器,返回统一的错误DTO,这样OpenAPI只需引用该DTO即可,更便于维护。
内容的提问来源于stack exchange,提问作者Rodrigo Lira
相关产品推荐
相关产品推荐

