2015-03-02 224 views
6

所以我想改變用於通過DropWizard資源來驗證模型的驗證消息。覆蓋DropWizard ConstraintViolation消息

我正在使用java bean驗證註釋。例如,這裏是我想要驗證的字段之一:

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

我可以按照預期使用驗證器來測試此工作。

然而,當我使用DropWizard做資源上的驗證,加入了一些額外的東西到該消息。我看到的是這樣的 - password Password must not be empty. (was null)我發現的代碼,這是否在這裏 - https://github.com/dropwizard/dropwizard/blob/master/dropwizard-validation/src/main/java/io/dropwizard/validation/ConstraintViolations.java

特別是這種方法 -

​​

有什麼辦法,我可以覆蓋這個行爲?我只是想顯示我的註釋設置消息...

回答

5

ConstraintViolationExceptionMapper是它使用的方法之一。爲了覆蓋它,你需要註銷它並註冊你自己的ExceptionMapper

刪除異常映射器(S)

Dropwizard 0.8

以下內容添加到您的YAML文件。請注意,它將刪除dropwizard添加的所有默認異常映射器。

server: 
    registerDefaultExceptionMappers: false 

Dropwizard 0.7.x

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

創建並添加自己的異常映射

public class ConstraintViolationExceptionMapper implements ExceptionMapper<ConstraintViolationException> { 

    @Override 
    public Response toResponse(ConstraintViolationException exception) { 
     // get the violation errors and return the response you want. 
    } 
} 

,並在您的應用程序類添加你的異常映射。

public void run(T configuration, Environment environment) throws Exception { 
    environment.jersey().register(ConstraintViolationExceptionMapper.class); 
} 
+0

我喜歡[盧卡斯Wiktor的的答案](http://stackoverflow.com/a/30799426/1891566)更好,因爲他重新instates其他異常映射器說的這第一步答案刪除,有效地改變* ConstraintValidationException *的映射器* – 2016-02-23 17:43:35

6

這裏是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

+1

這應該是被接受的答案,因爲當前的移除比OP要求的更多異常映射器。 – 2016-02-23 17:44:43