如何在@ApiModelProperty中设置示例值,以使HTTP状态代码返回不同的值?

问题描述

我有一个名为ErrorDetails的类,它是所有错误响应的模板。

public class ErrorDetails {
  private Date timestamp;
  private String message;
  private String details;
  private int code;

  public ErrorDetails(Date timestamp,String message,String details,int code) {
    this.timestamp = timestamp;
    this.message = message;
    this.details = details;
    this.code = code;
  }
}

现在,为了显示示例值,我们使用招摇注解:@ApiModel@ApiModelProperty。但是我想针对各个错误响应显示不同的样本。 例如,code 400应具有示例消息:Page not found,对于code 500,将具有不同的示例消息。我该如何实现?我只能为特定情况指定一个示例值。有没有办法以编程方式处理样本值?我探索了以下方式:

  1. 在全局摘要配置中设置了通用响应: 这里的问题是我可能对单独的代码404会有不同的错误响应。例如:“找不到员工”,“找不到存储”等。如果我具有全局配置,则无法实现。
  2. @Example@ApiResponse一起使用: 这里的问题是这无法正常工作,并且springfox开发团队建议使用@ApiModelProperty代替这种方法。

@ApiResponse(code = 500,message = "Internal server error",response = ErrorDetails.class,examples = @Example(value = @ExampleProperty(value = "{\"timestamp\": \"1598947603319\",\"message\":\"Operation failed\",\"details\":\"Operation failed due to Runtime exception\",\"code\": \"500\"}",mediaType = "application/json")))

上面的代码不起作用,我得到以下输出:

enter image description here

有人可以建议我如何解决上述问题?或如何在@ApiModelProperty中动态设置值?

解决方法

如果您只需要显示在什么状态代码上附加了什么消息,那么这里是示例

    @PostMapping(value = "/api/posts")
    @ApiOperation(value = "Create post.")
    @ApiResponses({
        @ApiResponse(code = 200,message = "Post created successfully",response = PostResponse.class),@ApiResponse(code = 404,message = "Blog does not exist",response = ApiError.class),@ApiResponse(code = 409,message = "Post already exists",@ApiResponse(code = 422,message = "Block content full",response = ApiError.class)
})
PostResponse createPost(...){
  ...
}
,

显然,我必须创建代表这些错误中的每一个的不同类,并从@ApiResponse进行链接。我不可能只有一个模型类可以针对所有不同的HTTP状态抛出不同的样本响应。

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...