【发布时间】:2022-02-02 16:34:09
【问题描述】:
我需要用 OpenAPI 记录我的 SpringBoot API 及其可能的异常, 我正在使用 SpringDoc-OpenAPI https://springdoc.org/。
为了处理 NotFound 案例,我创建了这个异常类:
import org.springframework.http.HttpStatus;
import org.springframework.web.server.ResponseStatusException;
public class NotFoundException extends ResponseStatusException {
public NotFoundException() {
super(HttpStatus.NOT_FOUND);
}
}
还有这个@RestControllerAdvice
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
@RestControllerAdvice
public class GlobalControllerExceptionHandler {
@ExceptionHandler(NotFoundException.class)
@ResponseStatus(HttpStatus.NOT_FOUND)
public ResponseEntity<String> handleNotFoundException(RuntimeException ex) {
return new ResponseEntity<>(ex.getMessage(), HttpStatus.NOT_FOUND);
}
}
我面临的问题是生成的OpenAPI yaml文件有
responses:
"404":
description: Not Found
content:
'*/*':
schema:
type: string
适用于所有@RestController 端点,而不是仅适用于带有throws NotFoundException 的方法。
如何限制 @ControllerAdvice(或 OpenAPI),只为带有 throwing 签名的方法生成 404 响应文档?
除了@RestControllerAdvice,我还需要使用其他东西吗? 我想避免必须注释每个方法。
【问题讨论】:
标签: spring-boot openapi springdoc