gpt4 book ai didi

java - 覆盖 DropWizard ConstraintViolation 消息

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:50:33 24 4
gpt4 key购买 nike

So I want to change the validation messages used to validate a model through a DropWizard resource.

I'm using java bean validation annotations. For example here is one of the fields I want to validate:

@NotEmpty(message = "Password must not be empty.")

I can test this works as expected using a validator.

However when I use DropWizard to do the validation on the resource it adds some extra stuff to that message. What I see is this - password Password must not be empty. (was null) and I've found the code that does this here - https://github.com/dropwizard/dropwizard/blob/master/dropwizard-validation/src/main/java/io/dropwizard/validation/ConstraintViolations.java

Specifically this method -

public static <T> String format(ConstraintViolation<T> v) {
if (v.getConstraintDescriptor().getAnnotation() instanceof ValidationMethod) {
final ImmutableList<Path.Node> nodes = ImmutableList.copyOf(v.getPropertyPath());
final ImmutableList<Path.Node> usefulNodes = nodes.subList(0, nodes.size() - 1);
final String msg = v.getMessage().startsWith(".") ? "%s%s" : "%s %s";
return String.format(msg,
Joiner.on('.').join(usefulNodes),
v.getMessage()).trim();
} else {
return String.format("%s %s (was %s)",
v.getPropertyPath(),
v.getMessage(),
v.getInvalidValue());
}
}

Is there any way I can override this behaviour? I just want to display the message that I set in the annotation...

最佳答案

这是 dropwizard 0.8 中的程序化解决方案:

public void run(final MyConfiguration config, final Environment env) {
AbstractServerFactory sf = (AbstractServerFactory) config.getServerFactory();
// disable all default exception mappers
sf.setRegisterDefaultExceptionMappers(false);
// register your own ConstraintViolationException mapper
env.jersey().register(MyConstraintViolationExceptionMapper.class)
// restore other default exception mappers
env.jersey().register(new LoggingExceptionMapper<Throwable>() {});
env.jersey().register(new JsonProcessingExceptionMapper());
env.jersey().register(new EarlyEofExceptionMapper());
}

我认为它比配置文件更可靠。如您所见,它还支持所有其他 default exception mappers .

关于java - 覆盖 DropWizard ConstraintViolation 消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28806959/

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