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

问题描述 投票:0回答:1

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

spring-boot spring-webflux swagger-codegen
1个回答
0
投票

正如您自己指出的那样,默认的错误响应有效负载是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添加到方法的response@ApiResponse属性中,您将获得所需的结果

@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);
}

Swagger result

© www.soinside.com 2019 - 2024. All rights reserved.