spring - 使用自定义验证器进行 Spring Bean 验证
问题描述
我已经实现了自定义大小验证,以便将“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) {
...
}
如何获取原始注释的错误代码,以便将其添加到我的响应中?
我发现它exception.getFieldError().getArguments()
包含一个数组,其中包含我想要的值,SpringValidatorAdapter.ResolvableAttribute
但我不知道如何使用它。
解决方案
我能想到的最好的方法是将 ajavax.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 ...;
}
这行得通,但我觉得应该有更好的方法来做到这一点。
推荐阅读
- python - bucket.blob.upload_from_string 返回“ValueError:无无法转换为 unicode”
- javascript - 从 ajax 获取请求的数据
- flutter - 如何在颤振中实现这一点?
- popup - Kivy 从弹出窗口获取值并在屏幕上使用它
- android - ExoPlayer 中的自定义时间栏
- python - Copy Multiple Lines to variable in python using pyperclip
- kdb - 如何在 kdb 中删除具有重复值的行?
- svn - 表示修改的输出合并文件
- javascript - 在角度材料中的 mat-multiple 选择中添加搜索功能
- mysql - 如何损坏 mariaDB 中的 InnoDB 表以及如何检查表是否损坏?