【问题标题】:How to change the Validation Error behaviour for Dropwizard?如何更改 Dropwizard 的验证错误行为?
【发布时间】:2015-06-12 02:17:19
【问题描述】:

在 Dropwizard 中,我对资源方法使用 @Valid 注释:

public class Address {
  @NotNull
  String street
  ...
}

@Path("/address")
@Produces(MediaType.APPLICATION_JSON)
public class AddressResource {
  @POST
  public MyResponse addAddress(@Valid Address address) {
    if (address == null) {
      throw new WebApplicationException("address was null");
    }
    ...
  }
}

在应用程序启动时,我注册了一个自定义 WebApplicationExceptionMapper,它处理 WebApplicationExceptions。因此,对于值为 null 的地址,会在生成有用响应的映射器中引发和处理异常。但是,如果地址不为空但street 为空,Dropwizard 会自动生成响应并将其发送给客户端(我不喜欢)。

我如何干扰这个响应,以便最终它也被映射器处理?

【问题讨论】:

    标签: java bean-validation jersey-2.0 dropwizard validationerror


    【解决方案1】:

    Dropwizard 注册自己的约束违规异常映射器,您可以覆盖它。

    由于 Jersey 尚不支持异常映射器 (https://java.net/jira/browse/JERSEY-2437) 上的 @Priority 注释,因此您应在注册自己的映射器之前禁用 Dropwizard 映射器的注册。这是应用程序的 run 方法和异常映射器的片段:

    @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) {
        ...
        }
    }
    

    【讨论】:

    • 我相信这是正确的方法(关闭默认值,添加您自己的,然后添加回默认值)。我最近看到,如果上面没有完成,异常映射器会被随机拾取(有时是我的,有时是默认值)。并看到这个答案,detailing the same behavior;还有check this out
    【解决方案2】:

    在较新的 Dropwizard 版本(例如 0.9.2)中,我必须这样做:

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

    【讨论】:

    • 伟大的贡献。 true 标志向日志添加更多详细信息。
    猜你喜欢
    • 2023-03-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-27
    • 1970-01-01
    • 2020-08-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多