У меня есть контроллер, который служит веб-службой REST, и один из моих методов ожидает модель, которая в этой модели имеет переменную-член типа MyObjectId
.@ExceptionHandler не перехватывает исключения из Spring Formatters
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);
}
В моей весне-servlet.xml Я зарегистрировал форматировщик:
<bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
<property name="formatters">
<set>
<bean class="com.foo.MyObjectIdFormatter"/>
</set>
</property>
</bean>
Теперь моя проблема заключается в том, что, когда исключение из Formatter он не поймал ни одной из @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);
}