Reputation: 10549
I have Spring Boot MVC application where exceptions are handled within a general @ControllerAdvice
. Some of them do not include a response body, like for instance:
@ExceptionHandler(EntityNotFoundException.class)
@ResponseStatus(NOT_FOUND)
void handleEntityNotFound() {
}
Everything works fine, but I run into issues if I want to expose my endpoints with SpringDoc. The exception handler is picked up correctly, however, the Swagger-UI displays a random response for 404
s:
Note, that this even isn't the response of the GET endpoint in question here, but a response from a method from a different RestController
.
What do I have to do to hide wrong response? I already tried
@ApiResponse(responseCode = "404", description = "Not found", content = @Content)
@ExceptionHandler(EntityNotFoundException.class)
@ResponseStatus(NOT_FOUND)
void handleEntityNotFound() {
}
as suggested in the docs, but that does not work.
Upvotes: 2
Views: 3579
Reputation: 3766
If you don't want to hide it and want to show the appropriate response, one way to do that is you can define a string as an example
public static final String exampleInternalError = "{\r\n"
+ " \"code\": 404,\r\n"
+ " \"message\": \"Resource not found\"\r\n" + "}";
same is used to show the example as
@ApiResponse(responseCode = "404",
description = "Resource not found",
//And different example for this error
content = @Content(schema = @Schema(implementation = ErrorResponse.class),
examples = @ExampleObject(description = "Internal Error", value = exampleInternalError)))
Upvotes: 0