使用自定义验证器进行Spring Bean验证

athom:

我已经实现了自定义大小验证,以便将“ errorCode”添加到验证错误中。

@Target({ METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER, TYPE_USE })
@Retention(RUNTIME)
@Documented
@Constraint(validatedBy = { StringLengthValidator.class })
public @interface StringLength {

    String message() default "Size must be between {min} and {max}";

    Class<?>[] groups() default { };

    Class<? extends Payload>[] payload() default { };

    long min() default 0L;

    long max();

    String errorCode() default "";

}

我在DTO中用以下注释了一个字段:

@StringLength(min = 5, max = 400, errorCode = "1000001")

在中,@RestControllerAdvice我添加了以下内容:

@ExceptionHandler({WebExchangeBindException.class})
Mono<ResponseEntity<...>> webExchangeBindException(WebExchangeBindException exception, ServerHttpRequest request) {
    ...
}

如何将原始注释的errorCode添加到响应中?

我发现其中exception.getFieldError().getArguments()包含一个数组,该数组具有要包装在其中的值,SpringValidatorAdapter.ResolvableAttribute但我不知道如何使用它。

athom:

我能想到的最好的方法是将a javax.validation.Validator注入。@RestControllerAdvice然后使用以下@ExceptionHandler命令获取验证批注的“ errorCode”值。

@ExceptionHandler({WebExchangeBindException.class})
Mono<ResponseEntity<...>> webExchangeBindException(WebExchangeBindException exception, ServerHttpRequest request) {
    Set<ConstraintViolation<Object>> violations = validator.validate(exception.getTarget());
    violations.stream()
        .findFirst()
        .ifPresent(violation -> /*Assign error here */ ... violation.getConstraintDescriptor().getAttributes().get("errorCode"));
    return ...;
}

这可行,但是我认为应该有更好的方法来做到这一点。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章