gpt4 book ai didi

Java:Spring RestControllerAdvice 异常处理程序中未触发自定义枚举 validator 注释

转载 作者:行者123 更新时间:2023-12-01 17:52:09 24 4
gpt4 key购买 nike

自定义枚举 validator 注释接口(interface):

@Target({METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER, TYPE_USE})
@Retention(RUNTIME)
@Documented
@Constraint(validatedBy = PanTypeSubSetValidator.class)
public @interface PanTypeSubset {
PanType[] anyOf();
String message() default "must be any of {anyOf}";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}

以及实际实现:

public class PanTypeSubSetValidator implements ConstraintValidator<PanTypeSubset, PanType> {
private PanType[] subset;

@Override
public void initialize(PanTypeSubset constraint) {
this.subset = constraint.anyOf();
}

@Override
public boolean isValid(PanType value, ConstraintValidatorContext context) {
return value == null || Arrays.asList(subset).contains(value);
}
}

以及请求 DTO 中的用法:

@SuperBuilder
@Data
@NoArgsConstructor
public class PanBaseRequestDto {

@NotNull(message = "'PANTYPE' cannot be empty or null")
@PanTypeSubset(anyOf = {PanType.PAN, PanType.TOKEN}, message = "yesssss")
private PanType panType;

}

问题是这个注释似乎永远不会被触发。在实际验证之前,我在 @RestControllerAdvice DefaultExceptionHandler 实现中遇到了另一个异常:

Handling generic exception: (Invalid JSON input: Cannot deserialize value of type `...pantoken.PanType` from String "PAN1": not one of the values accepted for Enum class: [TOKEN, PAN]; nested exception is com.fasterxml.jackson.databind.exc.InvalidFormatException: Cannot deserialize value of type `...pantoken.PanType` from String "PAN1": not one of the values accepted for Enum class: [TOKEN, PAN]

最佳答案

通过在ENUM类中创建自定义@JsonCreator函数解决了这个问题。这不是最好的方法,因为我们在向最终客户端显示错误时丢失了用户提交的值,但这对我来说没问题。

@JsonCreator
public static PanType create(String value) {
if (Objects.isNull(value)) {
return null;
}

return Arrays.stream(PanType.values())
.filter(v -> value.equals(v.getType()))
.findFirst()
.orElse(PanType.UNKNOWN);
}

关于Java:Spring RestControllerAdvice 异常处理程序中未触发自定义枚举 validator 注释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60777960/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com