首页 > 解决方案 > 如何在 swagger 3.0.0 中映射响应错误模型?

问题描述

我正在通过 springfox-boot-starter 将我的 swagger 配置从 2.9 升级到 3.0.0,并且我正在关注https://springfox.github.io/springfox/docs/snapshot/ - 非常有用。

我坚持升级以下方法:

当前实施:

private ResponseMessage badRequestErrorResponse() {

        return new ResponseMessageBuilder().code(HttpServletResponse.SC_BAD_REQUEST)
                                           .message(HttpStatus.BAD_REQUEST.getReasonPhrase())
                                           .responseModel(
                                                   new ModelRef(ErrorResponse.class.getSimpleName()))
                                           .build();
    }

升级代码

private Response badRequestErrorResponse() {

        return new ResponseBuilder().code(String.valueOf(HttpServletResponse.SC_BAD_REQUEST))
                .description(HttpStatus.BAD_REQUEST.getReasonPhrase())
                . /* How to assign error Model here*/
                .build();
    }

请帮助映射 responseModel(在上面的代码中标记)。

我的 ErrorResponse 类是:

@Getter
public class ErrorResponse {

    @JsonProperty("error-code")
    private final int errorCode;

    @JsonIgnore
    private final HttpStatus status;

    @JsonProperty("error-message")
    private final String errorMessage;

    @JsonProperty("timestamp")
    private final Instant timestamp = Instant.now();

    @JsonInclude(JsonInclude.Include.NON_NULL)
    private Map<String, Map<String, List<String>>> requestParameterErrors;

    public ErrorResponse(final ErrorCode errorCodes,
                         final HttpStatus status,
                         final Map<String, Map<String, List<String>>> errors) {

        this.errorCode = errorCodes.getCode();
        this.status = status;
        this.errorMessage = errorCodes.getDefaultErrorMessage();
        if (MapUtils.isNotEmpty(errors)) {
            this.requestParameterErrors = errors;
        }
    }

    public ErrorResponse(final ErrorCode errorCode,
                         final HttpStatus status) {

        this.errorCode = errorCode.getCode();
        this.status = status;
        this.errorMessage = errorCode.getDefaultErrorMessage();
    }

    public ErrorResponse(final int errorCode,
                         final HttpStatus status,
                         final String errorMessage) {

        this.errorCode = errorCode;
        this.status = status;
        this.errorMessage = errorMessage;
    }

    public ErrorResponse(final HttpStatus status,
                         final AbstractRPRuntimeException exception) {

        this(exception.getErrorCode().getCode(), status, exception.getMessage());
    }
}

标签: javaspring-bootswaggerspringfoxspringfox-boot-starter

解决方案


推荐阅读