我有一个控制器作为REST Web服务,我的一个方法是期待一个模型,在这个模型中我有一个MyObjectId
类型的成员变量。
public class MyModel {
private MyObjectId objectId;
public MyObjectId getMyObjectId() {
return objectId;
}
public void setMyObjectId(final MyObjectId objectId) {
this.objectId = objectId;
}
}
我为MyObjectId定制了Formatter
(org.springframework.format),这是我的解析方法:
@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>
现在我的问题是,当从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);
}
答案 0 :(得分:0)
我的情况相同
我不处理Formatter
@Controller
例外情况
检查以下内容:
codes [typeMismatch.filterModel.myObjectId,typeMismatch.myObjectId,typeMismatch.com.foo.MyObjectId,typeMismatch];
我建议您解决ValidationMessages.properties
(需要配置LocalValidatorFactoryBean
和ReloadableResourceBundleMessageSource
)
例如我有
typeMismatch.person.dateBirth=Invalid data, format for Date of Birth is incorrect!
然后假设明智和友好的用户根据格式化程序写了一个无效的日期,我的DateFormatter
类就像你的情况一样抛出异常,但是因为我已经定义了代码typeMismatch.person.dateBirth
的错误消息在我的网络表单中显示。
观察我们的代码在某些方面是相似的。我认为如果某些codes
存在以显示相应的消息,那么Spring会在某处显示,因为您没有代码,异常堆栈跟踪仍然存在,在我的例子中我是如何获得代码和定制的消息,它以我的网络形式呈现。
我还没有测试该自定义错误消息应该如何适合REST
。但在我的情况下,如果某些Formatter
引发错误,我确信code
文件中存在ValidationMessages.properties
。