如何捕获ConversionFailedException?

时间:2016-08-18 10:58:58

标签: java spring spring-mvc

我在Spring MVC Web应用程序中使用FormatterConverter。是否有正确的方法来捕捉ConversionFailedException?我想做其他事情,而不是让我的页面抛出JasperException

请注意:我不能直接使用FormatterConverter。我configured Spring以某种方式为我做这件事。因此,在表单中,我有一个String,但使用已注册的ConversionService,它会返回到我的控制器@ModelAttribute - 带注释的参数作为对象。

3 个答案:

答案 0 :(得分:2)

您可以使用@ExceptionHandler,将其添加到您的班级

@ExceptionHandler(ConversionFailedException.class)
public void handleError(ConversionFailedException ex) {
    // handle the exception
}

Reference

答案 1 :(得分:1)

一个简单的try / catch块应该可以工作。

try {
    // piece of code that throws the exception...
} catch (ConversionFailedException exception) {
    // you have caught the exception, do whatever you want here...
}

答案 2 :(得分:0)

创建自己的ConversionService扩展默认值并覆盖convert方法以捕获转换错误,而是提供所需的行为(例如记录转换错误)。