Override DropWizard ConstraintViolation message

前端 未结 3 368
终归单人心
终归单人心 2020-12-11 05:35

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

相关标签:
3条回答
  • 2020-12-11 06:11

    ConstraintViolationExceptionMapper is the one which uses that method. In order to override it, you need to deregister it and register your own ExceptionMapper.

    Remove the exception mapper(s)

    Dropwizard 0.8

    Add the following to your yaml file. Note that it will remove all the default exception mappers that dropwizard adds.

    server:
        registerDefaultExceptionMappers: false
    

    Dropwizard 0.7.x

    environment.jersey().getResourceConfig().getSingletons().removeIf(singleton -> singleton instanceof ConstraintViolationExceptionMapper);
    

    Create and add your own exception mapper

    public class ConstraintViolationExceptionMapper implements ExceptionMapper<ConstraintViolationException> {
    
        @Override
        public Response toResponse(ConstraintViolationException exception) {
            // get the violation errors and return the response you want.
        }
    }
    

    and add your exception mapper in your application class.

    public void run(T configuration, Environment environment) throws Exception {
      environment.jersey().register(ConstraintViolationExceptionMapper.class);
    }
    
    0 讨论(0)
  • 2020-12-11 06:25

    Here is a programmatic solution in 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());
    } 
    

    I think it's more reliable than a config file. And as you can see it also enables back all other default exception mappers.

    0 讨论(0)
  • 2020-12-11 06:25

    @ValidationMethod should be useful here. isn't it?

    http://www.dropwizard.io/0.9.0/docs/manual/validation.html

    @ValidationMethod(message="Password cannot be empty")
    @JsonIgnore
    public boolean isPasswordProvided() {
        return false if password not provided;
    }
    
    0 讨论(0)
提交回复
热议问题