springdoc中的默认响应类

时间:2020-03-26 14:25:20

标签: springdoc springdoc-openapi-ui

我正在尝试向API中的所有端点添加默认错误模型,以获取一些错误代码。

通过阅读以下问题,我找到了部分解决方案:

这是我为自定义创建的bean:

    @Bean
    public OpenApiCustomiser customOpenApiCustomiser() {
        return openApi -> {
            openApi.getPaths().values().forEach(pathItem -> pathItem.readOperations().forEach(operation -> {

                Schema sharedErrorSchema = ModelConverters.getInstance()
                        .read(Error.class)
                        .getOrDefault("Error", new Schema());

                MediaType sharedMediaType = new MediaType().schema(sharedErrorSchema);
                Content sharedContent = new Content()
                        .addMediaType(APPLICATION_JSON_VALUE, sharedMediaType);

                ApiResponses apiResponses = operation.getResponses();

                ApiResponse response = new ApiResponse()
                        .description("Unhandled server error")
                        .content(sharedContent);
                apiResponses.addApiResponse("500", response);
            }));
        };
    }

我的Error类看起来像:

public class Error {
    private String message;
    private List<ErrorItem> errorItems;
}

问题是,当我在swagger-ui中打开端点定义之一时,出现以下错误:

Could not resolve reference: Could not resolve pointer: /components/schemas/ErrorItem does not exist in document

如何为ErrorItem定义架构,使其可用于swagger-ui?

我正在使用:

  • Spring Boot => 2.2.4。发布
  • springdoc-openapi-ui => 1.3.0
  • springdoc-openapi-security => 1.3.0

1 个答案:

答案 0 :(得分:6)

我遇到了类似的问题,并在今天解决了该问题:

首先,您必须将所有java类型添加到组件中:

// add Error and ErrorItem to schema
openApi.getComponents().getSchemas().putAll(ModelConverters.getInstance().read(Error.class));
openApi.getComponents().getSchemas().putAll(ModelConverters.getInstance().read(ErrorItem.class));

然后,您必须创建一个Schema-Ref才能在响应中使用它:

// add default responses
// Ref to Error-Object (added in step above)
Schema errorResponseSchema = new Schema();
errorResponseSchema.setName("Error");
errorResponseSchema.set$ref("#/components/schemas/Error");

现在您可以使用此参考。在此示例中,我仅对BadRequest使用Error,所有其他默认响应均不使用架构。根据需要进行更改:-)

openApi.getPaths().values().forEach(pathItem -> pathItem.readOperations().forEach(operation -> {
  ApiResponses apiResponses = operation.getResponses();
  apiResponses.addApiResponse("400", createApiResponse("BadRequest", errorResponseSchema));
  apiResponses.addApiResponse("403", createApiResponse("Forbidden", null));
  apiResponses.addApiResponse("404", createApiResponse("Not Found", null));
  apiResponses.addApiResponse("500", createApiResponse("Server Error", null));
}));

createApiResponse只是一个简单的私有函数:

private ApiResponse createApiResponse(String message, Schema schema) {
  MediaType mediaType = new MediaType();
  mediaType.schema(schema);
  return new ApiResponse().description(message)
                .content(new Content().addMediaType(org.springframework.http.MediaType.APPLICATION_JSON_VALUE, mediaType));
}

确保正确导入Error.class,默认情况下为java.lang.Error。