这是我的验证类,它实现了ConstraintValidator
@Slf4j
public class DocumentMetaDataValidation implements ConstraintValidator<DocumentMetaDataValidator, DocumentMetaDataApplicationRequest> {
@Override
public boolean isValid(DocumentMetaDataApplicationRequest dataApplicationRequest, ConstraintValidatorContext constraintValidatorContext) {
constraintValidatorContext.disableDefaultConstraintViolation();
if(!Objects.nonNull(dataApplicationRequest)) {
log.error("Request Parameter is null/empty : ");
constraintValidatorContext
.buildConstraintViolationWithTemplate("Required parameter DocumentMetaDataApplicationRequest cannot be null/empty")
.addConstraintViolation();
return false;
}
Set<String> documentTypeSet=new HashSet<>();
dataApplicationRequest.getDocumentDetails().stream().forEach(documentDetails ->
documentTypeSet.add(documentDetails.getDocumentType()));
if (documentTypeSet.size()!=dataApplicationRequest.getDocumentDetails().size()){
log.error("Duplicate document type present ");
constraintValidatorContext
.buildConstraintViolationWithTemplate("Duplicate document type present")
.addConstraintViolation();
return false;
}
return true;
}
}
这是我的控制器:
@PostMapping(path = "/{referenceId}")
public Mono<DocumentUploadResponse> upload(
@NotBlank(message = "reference Id cannot be blank")
@PathVariable(value = "referenceId") String referenceId,
@NotEmpty(message = "List should not be empty")
@DocumentValidator @RequestPart(value = "documents") List<FilePart> document,
@DocumentMetaDataValidator @Valid @NotNull(message = "DocumentMetadata cannot be null")
@RequestPart(value = "documentsMetaData") DocumentMetaDataApplicationRequest documentMetaDataApplicationRequest) {
log.info("inside DocumentStorageController : uploadDocument()");
return documentStorageService.upload(referenceId, document, documentMetaDataApplicationRequest);
}
这是我的验证器类
@Target( { FIELD, PARAMETER })
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Constraint(validatedBy = DocumentMetaDataValidation.class)
public @interface DocumentMetaDataValidator {
public String message() default ErrorMessage.VALIDATION_ERROR;
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
而不是得到错误为“重复的文档类型存在”im得到“上传.DocumentMetaDataApplicationRequest:其中upload是我的控制器中的方法,DocumentMetaDataApplicationRequest是我试图验证的类。
我试着浏览文档,似乎它附加了一个名为“propertyPath”的东西,我无法摆脱它。
2条答案
按热度按时间6rqinv9w1#
您可以通过实现自定义异常处理程序来重写该行为
在
ConstraintVoilationException
的情况下,您可以添加新的异常处理程序bybem2ql2#
在handleConstraintVoilation(ConstraintViolationException ex)中,可以获得所有消息的列表