【问题标题】:Swagger required parameter returns 500 when missing instead of 404Swagger 必需参数在丢失时返回 500 而不是 404
【发布时间】:2020-03-18 10:46:48
【问题描述】:
我有一个带有请求参数“myParam”的 REST 端点。这是一个必需的参数,没有这个参数,对此端点发出的任何 GET 请求都被视为错误请求。我用 Swagger 来强调这个参数是必须的,如下
@ApiParam(required = true) @RequestParam(value = "myParam") String myParam
问题是,当我通过 Postman 向此端点提交 GET 时,返回的 HTTP 错误是 500,表示未提供所需的参数 myParam。有什么方法可以重构它,以便如果 Swagger 标记为所需的参数丢失,则响应为 404?
【问题讨论】:
标签:
java
spring-boot
rest
swagger
【解决方案1】:
一种解决方案可能是创建一个类并使用@ControllerAdvice 对其进行注释。此类的方法负责处理作为参数传递的特定异常。在您的 500 错误中,应该有一个异常堆栈跟踪,例如 “由 ..org.somepackage.SomeException ... 引起”。
1) 您可以创建一个包含消息和 HttpStatus 代码的自定义类:
public class ExceptionResponse {
private HttpStatus httpStatus;
private String errorMessage;
//getters;setters;
}
2) @ControllerAdvice 带注释的类应如下所示:
@ControllerAdvice
public class RestExceptionHandler {
@ExceptionHandler(value = SomeException.class)
public ResponseEntity<ExceptionResponse> handleMissingRequiredParameters(SomeException ex) {
ExceptionResponse exceptionResponse = new ExceptionResponse();
exceptionResponse.setHttpStatus(HttpStatus.BAD_REQUEST);
exceptionResponse.setErrorMessage(ex.getMessage());
return new ResponseEntity<>(exceptionResponse, exceptionResponse.getHttpStatus());
}
}
现在,当SomeException 被抛出时,您将看到的实际响应是带有自定义httpStatus 和errorMessage 的ExceptionResponse JSON。