在 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 会自动生成响应并将其发送到客户端(我不喜欢这样做)。
如何干扰此响应,以便最终它也由映射器处理?
最佳答案
Dropwizard 注册自己的约束违规异常映射器,您可以覆盖该映射器。
由于 Jersey 尚不支持异常映射器 ( https://java.net/jira/browse/JERSEY-2437 ) 上的 @Priority
注释,因此您应该在注册自己的映射器之前禁用 Dropwizard 映射器的注册。以下是应用程序的运行方法和异常映射器的片段:
@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) {
...
}
}
关于java - 如何更改 Dropwizard 的验证错误行为?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29492359/