【发布时间】:2020-06-06 07:04:06
【问题描述】:
我正在验证休息端点的请求参数:
@Valid BoundingBox boundingBox
请求参数列表映射到BoundingBox 的实例。
在BoundingBox 类中,我使用注解进行字段验证,例如@Max、@Min 等。
为了处理任何无效的请求参数,我重写了
ResponseEntityExceptionHandler.handleMethodArgumentNotValid方法为:
@Override
protected ResponseEntity<Object> handleMethodArgumentNotValid(MethodArgumentNotValidException ex,
HttpHeaders headers, HttpStatus status,
WebRequest request) {
List<String> details = new ArrayList<>();
for(ObjectError error : ex.getBindingResult().getAllErrors()) {
details.add(error.getDefaultMessage());
}
ExceptionDetails error = new ExceptionDetails("Validation Failed", details);
return new ResponseEntity(error, HttpStatus.BAD_REQUEST);
}
注解ControllerAdvice 放置在处理程序类的顶部。
@Valid 似乎可以工作,因为请求没有通过并返回 BAD_REQUEST,但 handleMethodArgumentNotValid 方法没有被调用。
【问题讨论】:
-
您找到问题的答案了吗?我也有同样的问题。
标签: spring-boot controller-advice