How to change the Validation Error behaviour for Dropwizard?

三世轮回 提交于 2019-12-03 22:15:05

Dropwizard registers their own constraint violation exception mapper which you can override.

Since Jersey does not yet support the @Priority annotation on the exception mappers (https://java.net/jira/browse/JERSEY-2437), you should disable the registration of the Dropwizard's mappers before register your own. Here is an fragment of the Application's run method and an exception mapper:

@Override
public void run(
        final Configuration config,
        final Environment environment) throws Exception {
    ((DefaultServerFactory)config.getServerFactory()).setRegisterDefaultExceptionMappers(false);
    // Register custom mapper
    environment.jersey().register(new MyConstraintViolationExceptionMapper());
    // Restore Dropwizard's exception mappers
    environment.jersey().register(new LoggingExceptionMapper<Throwable>() {});
    environment.jersey().register(new JsonProcessingExceptionMapper());
    environment.jersey().register(new EarlyEofExceptionMapper());
    ...
}

@Provider
public class MyConstraintViolationExceptionMapper 
        implements ExceptionMapper<ConstraintViolationException> {

    @Override
    public Response toResponse(ConstraintViolationException exception) {
    ...
    }
}

In newer Dropwizard versions (for e.g. 0.9.2), I had to do:

env.jersey().register(new JsonProcessingExceptionMapper(true));

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!