在 SpringDoc OpenApi 中隐藏来自 ExceptionHandlers 的响应

Hiding response from ExceptionHandlers in SpringDoc OpenApi

我有 Spring 引导 MVC 应用程序,其中异常是在一般 @ControllerAdvice 中处理的。其中一些不包含响应主体,例如:

@ExceptionHandler(EntityNotFoundException.class)
@ResponseStatus(NOT_FOUND)
void handleEntityNotFound() {
}

一切正常,但如果我想用 SpringDoc 公开我的端点,我会 运行 遇到问题。异常处理程序被正确拾取,但是,Swagger-UI 显示 404s:

的随机响应

请注意,这甚至不是此处讨论的 GET 端点的响应,而是来自不同 RestController 的方法的响应。

我该怎么做才能隐藏错误的回复?我已经试过了

  @ApiResponse(responseCode = "404", description = "Not found", content = @Content)
  @ExceptionHandler(EntityNotFoundException.class)
  @ResponseStatus(NOT_FOUND)
  void handleEntityNotFound() {
  }

如文档中所建议,但这不起作用。

如果您不想隐藏它并想显示适当的响应,一种方法是您可以定义一个字符串作为示例

public static final String exampleInternalError = "{\r\n"
            + "  \"code\": 404,\r\n"
            + "  \"message\": \"Resource not found\"\r\n" + "}";

同样用于显示示例

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

您的问题已在 v1.4.1 中解决: