You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Swagger与Springfox不同响应状态码修改返回示例 201状态码隐藏Errors字段

针对不同响应码配置差异化返回示例的实现方案

方案1:SpringDoc OpenAPI 3.x 原生实现(主流版本推荐)

  • 适用场景:使用SpringDoc OpenAPI 3.x的项目,为官方原生支持的实现方式
  • 为不同响应码定义独立的@ApiResponse配置,通过content属性指定对应状态码的返回结构和示例,无需复用同一个全局DTO的注解配置
  • 201状态码的响应单独指定不含Errors字段的结构:可直接引用裁剪后的专用DTO,或者通过@ExampleObject手动编写示例内容
  • 参考代码:
@Operation(summary = "创建资源接口")
@ApiResponses(value = {
    @ApiResponse(responseCode = "201", description = "资源创建成功",
        content = @Content(mediaType = "application/json",
            schema = @Schema(implementation = CreateSuccessDTO.class), // 该DTO仅包含成功响应字段,无Errors属性
            examples = @ExampleObject(value = "{\"id\":123,\"name\":\"新建资源\",\"createTime\":\"2024-01-01T12:00:00\"}")
        )),
    @ApiResponse(responseCode = "400", description = "参数错误",
        content = @Content(mediaType = "application/json",
            schema = @Schema(implementation = CommonErrorDTO.class), // 该DTO包含Errors字段
            examples = @ExampleObject(value = "{\"code\":\"400\",\"message\":\"参数非法\",\"errors\":[\"name字段不能为空\"]}")
        ))
})
@PostMapping("/resource")
public ResponseEntity<CommonDTO> createResource(@RequestBody ResourceCreateReq req) {
    // 业务逻辑实现
}
  • 若不想额外维护多个DTO,可在全局通用DTO的Errors字段上添加@Schema(hidden = true),仅在非201的响应配置中单独指定展示该字段即可。

方案2:旧版Springfox 2.x/3.x 自定义扩展实现

  • 适用场景:仍在使用Springfox旧版本、不方便升级到SpringDoc的存量项目
  • 继承OperationBuilderPlugin接口自定义响应示例构建逻辑,通过判断响应码是否为201,动态过滤Errors字段的展示
  • 参考代码:
@Component
public class CustomResponseExampleBuilder implements OperationBuilderPlugin {
    @Override
    public void apply(OperationContext context) {
        List<Response> responses = context.operationBuilder().build().getResponses();
        responses.forEach(response -> {
            if ("201".equals(response.getCode())) {
                // 动态移除201响应示例中的errors字段
                Map<String, Model> models = context.getDocumentationContext().getAdditionalModels();
                models.values().forEach(model -> model.getProperties().remove("errors"));
            }
        });
    }

    @Override
    public boolean supports(DocumentationType delimiter) {
        return DocumentationType.SWAGGER_2.equals(delimiter) || DocumentationType.OAS_30.equals(delimiter);
    }
}

方案3:轻量实现(无需调整框架配置)

  • 适用场景:不想修改Swagger配置、仅需文档明确说明的场景
  • 给Errors字段的@ApiModelProperty注解添加required = false属性,同时在接口的201响应描述中明确标注「当前响应不会返回errors字段」,Swagger生成文档时会自动将该字段标记为可选,可手动清空示例中该字段的默认值。

内容的提问来源于stack exchange,提问作者Feiten

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 00:36:02