基于webflux的Spring-boot项目如何在Swagger中添加错误响应格式

How to add error response format in Swagger for a Spring-boot project based on webflux

我不知道如何在Swagger中为基于webflux的Spring-boot项目添加错误响应格式。 在我读过的所有教程中,我只找到了如何添加 200 响应格式,但我还需要显示 spring-boot 生成的错误(map<String, Object>)的格式。有什么想法请。

正如您自己指出的,默认的错误响应负载是 Map(具体来说是 Map<String, Object>,请参阅 DefaultErrorAttributes.getErrorAttributes(...))。将此指定为错误响应将无法满足您的需求。

相反,您可以使用默认错误映射的字段创建 class 指定错误响应负载。

public class SpringErrorPayload {
    public long timestamp;
    public int status;
    public String error;
    public String exception;
    public String message;
    public String path;

    public SpringErrorPayload(long timestamp, int status, String error, String exception, String message, String path) {
        this.timestamp = timestamp;
        this.status = status;
        this.error = error;
        this.exception = exception;
        this.message = message;
        this.path = path;
    }

    //removed getters and setters
}

然后,通过将 class 添加到方法 @ApiResponseresponse 属性,您将获得所需的结果

@ApiOperation("Create new something")
@ApiResponses(value = {
        @ApiResponse(code = 201, message = "New something successfully created"),
        @ApiResponse(code = 400, message = "Bad request, adjust before retrying", response = SpringErrorPayload.class),
        @ApiResponse(code = 500, message = "Internal Server Error", response = SpringErrorPayload.class )
})
@ResponseStatus(CREATED)
public SomethingPayload createSomething(@Valid @RequestBody final NewSomethingPayload newSomethingPayload) {
    return somethingService.createSomething(newSomethingPayload);
}