为了简单理解,如果使用@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层的休眠引起的,它将生成 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;
}