1)在服务器端创建自己的 RESTException。
2) 每当您响应该异常时;在 HTTP 标头中添加该异常消息。
3) 在 HTTP 协议中,使用服务器端异常的标头中可用的 errorCode && errorMessage 并在客户端对其进行解码,以在客户端显示有关该异常的有意义的数据。
HTTP Status: 500 - Internal Server Error
Response Headers:
Date=Wed, 09 Jan 2013 13:41:15 GMT
Server=Apache/2.2.17 (Unix) mod_ssl/2.2.17 OpenSSL/0.9.8e-fips-rhel5 mod_jk/1.2.28
errorCode=4567
errorMessage=invalid conference passcode
Accept-Charset=big5, big5-hkscs, compound_text, euc-jp, euc-kr, gb18030, gb2312, gbk, ibm-thai, ibm00858, ibm01140, ibm01141, ibm01142, ibm01143, ibm01144, ibm01145, ibm01146, ibm874, x-ibm875, x-ibm921, x-ibm922, x-ibm930, x-ibm933, x-ibm935, x-ibm937, x-ibm939, x- x-windows-50221, x-windows-874, x-windows-949, x-windows-950, x-windows-iso2022jp
Content-Length=6406
Connection=close
Content-Type=application/xml
Response Body:
4567: invalid conference passcode
com.xxx.exceptions.InvalidPasscodeException invalid conference passcode
at com.xxx.dao.impl.context.multipleconfs.ResLessConfDao.validatePasscode(ResLessConfDao.java:754)
at
下面是用 C# 客户端代码向服务器发送请求的示例;这有错误处理机制。
public static bool sendRequest(string requestURL, HTTPRequestMethod requestMethod,
NetworkCredential m_netCred, String xml, ErrorResponse m_objErrorResponse)
{
try
{
HttpWebRequest request = WebRequest.Create(requestURL) as HttpWebRequest;
request.PreAuthenticate = true;
request.Credentials = m_netCred;
request.Method = requestMethod.ToString();
request.AllowAutoRedirect = false;
request.ReadWriteTimeout = 100000;
request.ContentLength = xml.Length;
request.ContentType = "application/xml; encoding='utf-8'";
Debug.WriteLine("XML: {0}", xml);
StreamWriter postStream = new StreamWriter(request.GetRequestStream(), System.Text.Encoding.ASCII);
postStream.Write(xml);
postStream.Close();
WebResponse response = request.GetResponse();
response.Close();
}
catch (WebException webex)
{
var response = webex.Response as HttpWebResponse;
int errCode = 0;
if (response != null)
{
errCode = (int)response.StatusCode;
Debug.WriteLine("HTTP Status Code: " + (int)response.StatusCode);
if ((int)response.StatusCode != 500) //Other errors
{
m_objErrorResponse.UpdateErrorResponse(errCode.ToString(), response.StatusCode.ToString(), "");
}
else
{
m_objErrorResponse.UpdateErrorResponse(errCode.ToString(), response.StatusCode.ToString(),
response.Headers.ToString().Split('\n')[1].Substring(14).Trim());
}
}
return false;
}
return true;
}
}
Spring MVC REST 异常处理第 1 部分
Spring MVC REST 异常处理第 2 部分