我使用
Spring WebMVC来提供REST API.我用的方法就像
@RequestMapping(“/ path({id}”)void getById(@PathVariable(“id”)int id){}方法.
当客户端错误地将字符串而不是整数id放入查询时,我得到一个NumberFormatException,如:
java.lang.NumberFormatException: For input string: "dojo" at java.lang.NumberFormatException.forInputString(NumberFormatException.java:48) at java.lang.Long.parseLong(Long.java:410) at java.lang.Long.valueOf(Long.java:525) at org.springframework.util.NumberUtils.parseNumber(NumberUtils.java:158) at org.springframework.core.convert.support.StringToNumberConverterFactory$StringToNumber.convert(StringToNumberConverterFactory.java:59) at org.springframework.core.convert.support.StringToNumberConverterFactory$StringToNumber.convert(StringToNumberConverterFactory.java:1) at org.springframework.core.convert.support.GenericConversionService$ConverterFactoryAdapter.convert(GenericConversionService.java:420) at org.springframework.core.convert.support.ConversionUtils.invokeConverter(ConversionUtils.java:37) at org.springframework.core.convert.support.GenericConversionService.convert(GenericConversionService.java:135) at org.springframework.beans.TypeConverterDelegate.convertIfNecessary(TypeConverterDelegate.java:199) at org.springframework.beans.TypeConverterDelegate.convertIfNecessary(TypeConverterDelegate.java:104) at org.springframework.beans.SimpleTypeConverter.convertIfNecessary(SimpleTypeConverter.java:47) at org.springframework.validation.DataBinder.convertIfNecessary(DataBinder.java:526) at org.springframework.web.bind.annotation.support.HandlerMethodInvoker.resolvePathVariable(HandlerMethodInvoker.java:602) at org.springframework.web.bind.annotation.support.HandlerMethodInvoker.resolveHandlerArguments(HandlerMethodInvoker.java:289) at org.springframework.web.bind.annotation.support.HandlerMethodInvoker.invokeHandlerMethod(HandlerMethodInvoker.java:163) at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.invokeHandlerMethod(AnnotationMethodHandlerAdapter.java:414) at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.handle(AnnotationMethodHandlerAdapter.java:402) at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:771) at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:716) at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:647)
我的问题是现在,我怎么能优雅地抓住它?我知道Spring提供了@ExeptionHandler注释,但我不想一般地抓住NFE.我希望能够捕获所有解析异常,以便向客户端提供一个很好的错误消息.
有任何想法吗?
干杯,
一月