3 回答
TA贡献1820条经验 获得超9个赞
当您使用@Valid 时,您正在应用您在模型类字段上定义的验证,虽然有不同类型的验证,您可以选择@NotNull、@Max、@Min 等,您将获得匹配类型。
通常,所有这些都与在所有情况下都会抛出的MethodArgumentNotValidException并行。
来自官方文档
当验证用 @Valid 注释的参数失败时抛出异常。
当违反某些约束时,休眠实体管理器会抛出 ConstraintViolationException,因此这意味着您违反了正在使用的某些实体中的某些字段。
TA贡献1847条经验 获得超7个赞
为了简单理解,如果通过使用@Valid 注释在控制器/服务层进行验证,它会生成 MethodArgumentNotValidException,您可以为此添加处理程序并相应地返回响应,此类是 spring 框架的一部分,验证由 spring 框架执行见下面的示例
@ExceptionHandler(MethodArgumentNotValidException.class)
public ResponseEntity<Response> handleMethodArgumentNotValidException(MethodArgumentNotValidException ex) {
logger.info("Invalid arguments found : " + ex.getMessage());
// Get the error messages for invalid fields
List<FieldError> errors = ex.getBindingResult()
.getFieldErrors()
.stream()
.map(fieldError -> new FieldError(fieldError.getField(), fieldError.getDefaultMessage()))
.collect(Collectors.toList());
String message = messageSource.getMessage("invalid.data.message", null, LocaleContextHolder.getLocale());
Response response = new Response(false, message)
.setErrors(errors);
ResponseEntity<Response> responseEntity = ResponseEntity.status(HttpStatus.BAD_REQUEST).body(response);
return responseEntity;
}
并且如果您不使用@Valid 注释进行验证,并且在 jpa 层由 hibernate 引发异常,它会生成 ConstraintViolationException,此异常是 Javax bean 验证框架的一部分,并在执行持久性操作时引发(在实际执行 sql 之前)请参阅下面的示例
@ExceptionHandler(ConstraintViolationException.class)
public ResponseEntity<Response> handleConstraintViolationException(ConstraintViolationException ex) {
List<FieldError> errors = ex.getConstraintViolations()
.stream()
.map(constraintViolation -> {
return new FieldError(constraintViolation.getRootBeanClass().getName() + " " + constraintViolation.getPropertyPath(), constraintViolation.getMessage());
})
.collect(Collectors.toList());
String message = messageSource.getMessage("invalid.data.message", null, LocaleContextHolder.getLocale());
Response response = new Response(false, message)
.setErrors(errors);
ResponseEntity<Response> responseEntity = ResponseEntity.status(HttpStatus.BAD_REQUEST).body(response);
return responseEntity;
}
添加回答
举报
