我正在使用Spring Boot 2.2.0通过Java bean验证框架构建一个宁静的服务。 Hibernate-Validator在后台使用。验证效果很好,但在一个字段不符合约束条件后引发异常。我想先验证所有字段,然后再给消费者一个包含所有错误的响应。有可能吗?
假设您在请求中使用@Valid
批注,可以在MethodArgumentNotValidException
方法中使用一个@ExceptionHandler
以实现该目的。
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler(MethodArgumentNotValidException.class)
public List<String> handleValidationExceptions(MethodArgumentNotValidException ex) {
//get All errors with
ex.getBindingResult().getAllErrors();
//and map them
}