Search code examples
javaspring-bootswaggerswagger-uispringfox

How to set example values in @ApiModelProperty in such a way that different values are returned for HTTP status codes?


I have a class called ErrorDetails which is a template for all error responses.

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

Now, in order to display example values, we use swagger annotations: @ApiModel & @ApiModelProperty . But I want to display different samples for respective error responses. For example, code 400, should have sample message: Page not found and for code 500 will ahve different sample message. How do I achieve that? I can only specify one example value for a specific case. Is there a way to programmatically handle sample values? I have explored below ways:

  1. Having a generic response set at global docket config: Problem here is I might have different error response for code 404 alone. For example : "Employee not found", "Store not found" etc. This is impossible to achieve if I have global configuration.
  2. Using @Example with @ApiResponse: Problem here is this is not working & springfox dev team suggest to use @ApiModelProperty instead of this approach.

@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")))

The above code is not working and I get the below output: enter image description here

Can someone suggest me how to fix the above issue ? or how to set values dynamically in @ApiModelProperty ?


Solution

  • Apparently, I had to create different classes representing each one of these errors and link them from @ApiResponse. There's no way that I can have one single model class that can throw varying sample responses for all different HTTP status.