【发布时间】:2012-08-03 13:07:57
【问题描述】:
我有 Restful API,它在找不到项目时响应 404 错误,但根据未找到项目的原因(未知、不可用……)有不同的消息,使用 Spring 以这种方式完成MVC:
response.sendError(HttpServletResponse.SC_NOT_FOUND, "NOT_AVAILABLE");
(这适用于任何浏览器,以“NOT_AVAILABLE”作为消息显示 404 错误)
现在,我想使用 Spring RestTemplate 将该消息返回到我的 Java 代码中,以便管理它们。 我试过这个:
try {
rest.put(apiRootUrl + "/item/{itemId}", null, itemId);
} catch (HttpClientErrorException e) {
if (NOT_FOUND == e.getStatusCode()) {
switch (MyErrorCode.valueOf(e.getStatusText())) {
case NOT_AVAILABLE:
return displayNotAvailableError();
case UNKNOWN:
return displayUnknownError();
default:
// ...
}
}
}
但在 getStatusText() 中,我总是得到 NOT FOUND 标签(来自 404)而不是我的自定义值。
有人知道是否可以从 404 错误中检索自定义消息吗?那么怎么做呢?
非常感谢!
编辑:我在 Tomcat 服务器(发送 404 HTML 页面)上运行,这不会附加 Weblogic 服务器
【问题讨论】:
-
我通过分析这样的响应正文找到了解决方法:errorBody.substring(errorBody.indexOf("")+3, errorBody.indexOf("")) ;但它不是很整洁...... :-(
-
Tomcat服务器出现这种情况,Weblogic做对了,所以我认为这来自于tomcat的servlet API的实现
标签: rest error-handling resttemplate