出现未处理错误时 SpringBoot 应用程序的默认服务器响应是
{
"timestamp": 1594232435849,
"path": "/my/path",
"status": 500,
"error": "Internal Server Error",
"message": "this request is failed because of ...",
"requestId": "ba5058f3-4"
}
我想在应用程序路由的 Springdoc 注释中描述它。
假设有一个标准类
DefaultErrorResponse
(只是一个模拟名称),它可能如下所示:
@Operation(
// ... other details
responses = {
// ... other possible responses
@ApiResponse(
responseCode = "500",
content = @Content(schema = @Schema(implementation = DefaultErrorResponse.class)))
}
)
在更糟糕的情况下,这样的类不存在,Spring 仅使用
Map
来创建响应。那么这个注释将会更加详细,包括明确提及响应中包含的每个字段。
显然对于大多数路线来说,这部分
@ApiResponse(responseCode="500",...
是相同的,如果能减少重复就好了。
在文档中引入默认错误响应的描述的正确方法是什么?
对于错误处理,可以将@RestControllerAdvice与@ExceptionHandler结合使用,以重构错误处理。
这些 spring 注解由 springdoc-openapi 自动扫描。无需添加任何额外的 swagger 注释。
你几乎是正确的。 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;
}
}
并像这样使用它,正如您在问题中已经解释的那样:
@RestController
@ApiResponses({ //
@ApiResponse( //
responseCode = "500", //
description = "Internal failure", content = @Content( //
mediaType = "application/json", //
schema = @Schema(implementation = ErrorResponse.class))) //
})
class MyController { ...