2014-10-09 14 views
0

我有一個控制器作爲REST Web服務,我的方法之一是期待在這個模型中有一個模型,我有一個MyObjectId類型的成員變量。@ExceptionHandler不捕獲從格式器彈出的異常

public class MyModel { 

    private MyObjectId objectId; 

    public MyObjectId getMyObjectId() { 
     return objectId; 
    } 

    public void setMyObjectId(final MyObjectId objectId) { 
     this.objectId = objectId; 
    } 
} 

我有一個Formatter(org.springframework.format)爲MyObjectId自定義實現,這是我的解析方法:

@Override 
public MyObjectId parse(final String text, final Locale locale) throws ParseException { 
    // If the string is invalid it will throw an IllegalArgumentException 
    return MyObjectIdConvertor.convert(text); 
} 

在我爲spring-servlet.xml我註冊了我的格式:

<bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean"> 
    <property name="formatters"> 
     <set> 
      <bean class="com.foo.MyObjectIdFormatter"/> 
     </set> 
    </property>  
</bean> 

現在我的問題是,當一個異常從格式化拋出它沒有被任何@ExceptionHandler方法捕獲。因此,響應正在以這種格式輸出:

org.springframework.validation.BeanPropertyBindingResult: 1 errors Field error in object 'filterModel' on field 'myObjectId': rejected value [foo123123]; codes [typeMismatch.filterModel.myObjectId,typeMismatch.myObjectId,typeMismatch.com.foo.MyObjectId,typeMismatch]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [filterModel.myObjectId,myObjectId]; arguments []; default message [myObjectId]]; default message [Failed to convert property value of type 'java.lang.String' to required type 'com.MyObjectId' for property 'myObjectId'; nested exception is org.springframework.core.convert.ConversionFailedException: Failed to convert from type java.lang.String to type com.MyObjectId for value 'foo123123'; nested exception is java.lang.NumberFormatException: For input string: "foo123123"] 

我怎樣才能讓這種類型的異常開始由@ExceptionHandler抓獲。 我的異常處理方法,這一個:

@ExceptionHandler(Exception.class) 
@ResponseBody 
public ResponseEntity<String> handleException(final Exception ex) { 

    LOG.error("Error handling request", ex); 
    return new ResponseEntity<>(StringUtils.hasText(ex.getMessage()) ? ex.getMessage() : "Error handling request", HttpStatus.BAD_REQUEST); 
} 

回答

0

我有同樣的情況

我不處理在@Controller

Formatter例外檢查以下內容:

codes [typeMismatch.filterModel.myObjectId,typeMismatch.myObjectId,typeMismatch.com.foo.MyObjectId,typeMismatch]; 

我建議你在ValidationMessages.properties附近工作(你需要配置LocalValidatorFactoryBeanReloadableResourceBundleMessageSource

比如我有

typeMismatch.person.dateBirth=Invalid data, format for Date of Birth is incorrect! 

如果明智和友好的用戶根據格式化寫入一個無效的日期,那麼假設,我DateFormatter類,就像在你的情況下拋出一個異常,但因爲我已經定義代碼typeMismatch.person.dateBirth錯誤消息顯示在我的web表單中。

觀察我們的代碼在某些方面是相似的。我認爲如果有一些codes存在顯示適當的消息,因爲你有沒有代碼的異常堆棧跟蹤仍然存在,在我的情況下,我有我的代碼和自定義的消息,它是呈現在我的web表單。

我還沒有測試如何通過REST來定製錯誤信息。但在我的情況下,如果某些Formatter引發錯誤,我確信ValidationMessages.properties文件中存在code