如何在 springdoc Schema 中描述标准 Spring 错误响应?

diz*_*iaq 5 spring response spring-boot springdoc

如果出现未处理的错误,SpringBoot 应用程序的默认服务器响应是

{
    "timestamp": 1594232435849,
    "path": "/my/path",
    "status": 500,
    "error": "Internal Server Error",
    "message": "this request is failed because of ...",
    "requestId": "ba5058f3-4"
}
Run Code Online (Sandbox Code Playgroud)

我想在应用程序路由的 Springdoc 注释中描述它。

假设有一个标准类DefaultErrorResponse(只是一个模拟名称),它可能如下所示:

@Operation(
  // ... other details
  responses = {
    // ... other possible responses
    @ApiResponse(
      responseCode = "500",
      content = @Content(schema = @Schema(implementation = DefaultErrorResponse.class)))
  }
)
Run Code Online (Sandbox Code Playgroud)

在更糟糕的情况下,这样的类不存在,Spring 仅使用Map底层来创建响应。那么这个注释将更加详细,包括明确提及响应中包含的每个字段。

显然,对于大多数路线来说,这部分@ApiResponse(responseCode="500",...是相同的,并且最好减少重复。

在文档中引入默认错误响应描述的正确方法是什么?

Mat*_*ias 0

你几乎是正确的。Spring 使用org.springframework.boot.web.servlet.error.DefaultErrorAttributes它的默认错误处理,它是映射的包装器。

然而,该地图的内容很大程度上取决于您的配置。我只好创建自己的 DTO 来反映我的 Spring 配置,如下所示:

public class ErrorResponse {
  private Instant timestamp;
  private int status;
  private String error;
  private String path;
  public Instant getTimestamp() {
    return timestamp;
  }
  public void setTimestamp(Instant timestamp) {
    this.timestamp = timestamp;
  }
  public int getStatus() {
    return status;
  }
  public void setStatus(int status) {
    this.status = status;
  }
  public String getError() {
    return error;
  }
  public void setError(String error) {
    this.error = error;
  }
  public String getPath() {
    return path;
  }
  public void setPath(String path) {
    this.path = path;
  }
}
Run Code Online (Sandbox Code Playgroud)

并像这样使用它,正如您在问题中已经解释的那样:

@RestController
@ApiResponses({ //
    @ApiResponse( //
        responseCode = "500", //
        description = "Internal failure", content = @Content( //
            mediaType = "application/json", //
            schema = @Schema(implementation = ErrorResponse.class))) //
})
class MyController { ...
Run Code Online (Sandbox Code Playgroud)