问题描述
我一直在尝试使用简单的基于Spring 3的ReST Web服务进行异常处理。基于我所看到的一切,有一个错误阻止它自动使用@ResponseBody和@ExceptionHandler注释
I have been trying to get exception handling working in my simple Spring 3 based ReST web services. Based on everything I have seen, there is a bug that prevents this from working automatically with the @ResponseBody and @ExceptionHandler annotations
因此,直到Spring 3.1或3.0.6才支持它,当前执行异常处理的最佳方法是什么?我看过很多帖子,但没有找到一个对我有用的明确答案。一个理想的解决方案是自动提供对xml和json的支持
So given that it isn't supported until Spring 3.1 or 3.0.6, what is the current best method for doing exception handling? I have seen numerous posts but haven't found a clear answer that has worked for me. An ideal solution would be one that automatically provides support for both xml and json
- 我是否必须手动定义整个编组设置?这不会消除使用Spring 3休息支持值得的注释吗?
- 似乎是为了手动定义编组(即Jaxb2Marshaller)我需要添加一个新的依赖项spring-ws有点痛苦
- 是否更容易定义一个'Response'对象,我的所有方法返回并将所有函数包装在try / catch块中?
推荐答案
您可以重定向错误,然后在 @ResponseBody中返回一些内容
:
You can redirect on error and then return something in @ResponseBody
:
@ExceptionHandler(Exception.class)
public ModelAndView handleMyException(Exception exception) {
return new ModelAndView("redirect:errorMessage?error="+exception.getMessage());
}
@RequestMapping(value="/errorMessage", method=RequestMethod.GET)
@Responsebody
public String handleMyExceptionOnRedirect(@RequestParameter("error") String error) {
return error;
}
有点难看,但这只是解决方法,直到修复程序可用。
Little ugly, but this is just work around till the fix will be available.
这篇关于Spring 3,ReST,@ ResponseBody和@ExceptionHandler的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!