
[英]@ExceptionHandler doesn't catch exceptions being thrown from Spring Formatters
[英]@ExceptionHandler not catching exceptions being thrown from Spring Formatters
我有一个充当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
方法都不会捕获该@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);
}
我有同样的情况
我不处理@Controller
的Formatter
异常
检查以下内容:
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
因此错误消息会在我的Web表单中显示。
观察我们的代码在某种程度上是相似的。 我认为 Spring会在某些codes
存在的地方显示适当的消息,因为您没有代码,但异常堆栈跟踪仍然保留(在我的情况下,代码和自定义消息如何显示在Web表单中)。
我还没有测试该定制错误消息如何通过REST
很好地适合。 但是就我而言,如果某些Formatter
引发错误,我可以确定该code
存在于ValidationMessages.properties
文件中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.