【问题标题】:Catching 500-Internal Server Errors generically and returning a json一般捕获 500 内部服务器错误并返回 json
【发布时间】:2012-05-01 22:46:06
【问题描述】:
我正在使用 Spring MVC 编写一些 Spring REST 服务。我要求将任何 500(内部服务器错误)发送回打包为 Http Status = 500 的 json 和带有 json 字符串 [“Internal Server Error”] 的 Http Body。
为此,我正在扩展 OncePerRequestFilter 并检查 Http Response 的状态。然后,我正在使用所需的 json 响应构建主体。
尽管这达到了目的,但它很混乱。有没有更好的设计原则或者spring/json类可以用Spring配置达到同样的目的?
-戈茨
【问题讨论】:
标签:
json
spring
rest
jackson
【解决方案1】:
我相信你可以使用以下结构:
1) 将 HTTP 500 错误映射到某个视图:
<error-page>
<error-code>500</error-code>
<location>/errorView.htm</location>
</error-page>
2) 在您的控制器中创建视图,该视图将返回您需要的任何 Json 信息。
@RequestMapping(value="/errorView.htm",method = RequestMethod.GET)
public String handleGet(HttpServletRequest req) {
res.setStatus(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
res.setContentType("application/json");
res.getWriter().print("{\Error"\:\"Internal Server Error\"}");
}
希望对你有帮助。