Spring3 @ExceptionHandler用于ServletRequestBindingException
问题内容:
我正在使用一个默认的AnnotationMethodHandlerAdapter,我相信它应该启用对@ExceptionHandler的支持。不幸的是,如果对下面这样的处理程序方法的调用传入,则抛出ServletRequestBindingException,并且没有调用Exception处理程序。
@RequestMapping(value = "/v1/products/{code}", method = RequestMethod.GET, headers = "Accept=application/xml,application/json")
@ResponseBody
public ProductDemoDTO getProductByCode(@PathVariable final String code,
@RequestParam(required = false, defaultValue = "BASIC") final String options)
{
//omitted
}
这里是ExceptionHandler,从未调用过:
@ExceptionHandler(Throwable.class)
@ResponseBody
@ResponseStatus(value = HttpStatus.BAD_REQUEST)
//TODO not being called?
public void handleException(final Exception e, final HttpServletRequest request, final Writer writer) throws IOException
{
writer.write(String.format("{\"error\":{\"java.class\":\"%s\", \"message\":\"%s\"}}", e.getClass(), e.getMessage()));
}
有谁知道为什么不调用ExceptionHandler?
问题答案:
您无法使用spring自定义实现来处理它。
它可能不是一个很好的解决方案,但是您仍然可以使用web.xml <error-page>
标记来捕获它。您可以从此处捕获异常类型或错误代码。