我正在开发基于Spring Boot的REST API。我正在使用自定义ConstraintValidator注释验证输入实体。我的问题是我无法在响应中返回ConstraintViolationException消息。我的异常处理程序无法捕获异常(可能是因为异常处理包装在其他类型的异常中)。
请问您如何处理此问题的建议?
我已经在Internet上进行了搜索,但找不到适合我的解决方案,而且这样做也浪费了我几个小时。
示例注释:
@Documented
@Retention(RUNTIME)
@Target({FIELD, PARAMETER})
@Constraint(validatedBy = BirthDateValidator.class)
public @interface ValidBirthDate {
String message() default "The birth date is not valid.";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
验证者类:
public class BirthDateValidator extends FieldValidationBase implements ConstraintValidator<ValidBirthDate, LocalDate> {
private static final Logger LOGGER = LoggerFactory.getLogger(BirthDateValidator.class);
@Override
public void initialize(ValidBirthDate constraintAnnotation) {
}
@Override
public boolean isValid(LocalDate birthDate, ConstraintValidatorContext constraintValidatorContext) {
constraintValidatorContext.disableDefaultConstraintViolation();
LOGGER.info("Starting the validation process for birth date {}.", birthDate);
if(birthDate == null) {
constraintValidatorContext.buildConstraintViolationWithTemplate("The birth date is null.")
.addConstraintViolation();
return false;
}
//other validations
return true;
}
模型类:
public class Manager extends BaseUser {
//other fields
@Valid
@ValidBirthDate
private LocalDate birthDate;
//setters & getters
异常处理程序:
@ExceptionHandler(value = ConstraintViolationException.class)
public ResponseEntity handleConstraintViolationException(ConstraintViolationException ex, WebRequest request) {
List<String> errors = new ArrayList<>();
for (ConstraintViolation<?> violation : ex.getConstraintViolations()) {
errors.add(violation.getRootBeanClass().getName() + ": " + violation.getMessage());
}
Error response = new Error(errors);
return new ResponseEntity<Object>(response, new HttpHeaders(), BAD_REQUEST);
}
控制器:
@RestController
@RequestMapping(value = "/register", consumes = "application/json", produces = "application/json")
public class RegistrationController {
@Autowired
private RegistrationService registrationService;
@PostMapping(value = "/manager")
public ResponseEntity registerManager(@RequestBody @Valid Manager manager) {
registrationService.executeSelfUserRegistration(manager);
return new ResponseEntity<>(new Message("User " + manager.getEmailAddress() + " registered successfully!"), CREATED);
}
}
我得到了400响应代码,但是没有看到任何包含违反约束消息的响应主体。
[经过更多调试之后,我发现所有违反约束的条件都包装在MethodArgumentNotValidException
中(由于[C0]批注)-我必须在该异常内进行一些挖掘才能获取我的信息。
我已经从@Valid
覆盖了handleMethodArgumentNotValid()
方法,这就是我的工作方式:
ResponseEntityExceptionHandler
也许这可以帮助某人。