Web Services 在错误消息中附加propertyPath

5m1hhzi4  于 2023-03-23  发布在  其他
关注(0)|答案(2)|浏览(157)

这是我的验证类,它实现了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”的东西,我无法摆脱它。

6rqinv9w

6rqinv9w1#

您可以通过实现自定义异常处理程序来重写该行为

@RestControllerAdvice
public class GlobalExceptionHandler extends DefaultHandlerExceptionResolver {

    @ResponseStatus(BAD_REQUEST)
    @ExceptionHandler(value = {MethodArgumentNotValidException.class})
    protected ResponseEntity<Object> handleMethodArgumentNotValid(MethodArgumentNotValidException exception) {
        Map<String, String> errors = new HashMap<>();
        exception.getBindingResult().getAllErrors().forEach((error) -> {
            String fieldName = ((FieldError) error).getField();
            String errorMessage = error.getDefaultMessage();
            errors.put(fieldName, errorMessage);
        });
        return status(BAD_REQUEST).body(Collections.singletonMap("errors", errors));
    }
}

ConstraintVoilationException的情况下,您可以添加新的异常处理程序

@ResponseStatus(BAD_REQUEST)
@ExceptionHandler(value = {ConstraintViolationException.class})
protected ResponseEntity<Object> handleConstraintVoilation(ConstraintViolationException exception) {
    var violations = exception.getConstraintViolations();
    var errs = violations.
        stream().
        map(ConstraintViolation::getMessage).
        toList();
    Map<String, String> errors = new HashMap<>();
    return status(BAD_REQUEST).body(Collections.singletonMap("errors", errs));
}
bybem2ql

bybem2ql2#

在handleConstraintVoilation(ConstraintViolationException ex)中,可以获得所有消息的列表

var errors = new ArrayList<>(ex.getConstraintViolations());
    var errs = errors.stream().map(ConstraintViolation::getMessage).toList();

相关问题