How to hide the response from ExceptionHandlers for specific endpoints in Springdoc OpenAPI

Viewed 433

There is a Spring Boot application where exceptions are handled within a general @ControllerAdvice and several @ExceptionHandler. For example:

@ControllerAdvice
public class CustomExceptionHandler extends ResponseEntityExceptionHandler {
    @ResponseStatus(HttpStatus.FORBIDDEN) // 403
    @ExceptionHandler(AccessDeniedCustomException.class)
    public ResponseEntity<Object> handleAccessDeniedException(Exception ex, WebRequest request) {
        ...
    }

    @ResponseStatus(HttpStatus.NOT_FOUND) // 404
    @ExceptionHandler(NotFoundCustomException.class)
    public ResponseEntity<Object> handleNotFoundException(Exception ex, WebRequest request) {
        ...
    }
}

And with this configuration I get generated OpenAPI yaml file with the responses 403 and 404 for every endpoint.

I want to hide 403 for some specific endpoints, how can I do that?

I know about @Hidden annotation for handler method, but it removes response code from every endpoint. It isn't a desired behavior.

1 Answers

Hiding some responses from several endpoints can be done by using parameters in @ControllerAdvice annotation. You can split your handler methods by groups with the same behavior in different ControllerAdvice classes.

Then for one @ControllerAdvice annotation you can specify applied condition by basePackages or assignableTypes. See https://stackoverflow.com/a/36042624/3465146 answer for details.

But this solution isn't ideal if you have a lot of endpoints with common behavior and only a few exceptional endpoints with less responses. It would be great if there was a simple solution for this specific case, but I couldn't find it.

Related