簡體   English   中英

如何使用REST服務處理客戶端-服務器應用程序中的錯誤?

[英]How to handle errors in client-server application using REST services?

1)使用REST服務時如何處理客戶端-服務器應用程序中的錯誤? 有人可以幫我提供示例代碼,什么是處理以下代碼中錯誤消息的最佳方法。 例如,在創建服務的情況下,如何在客戶端和/或服務器端捕獲異常?

2)在出現錯誤和成功的情況下,如何將用戶轉發到其他頁面?


客戶

 $('#btnSignup').click(function(){ 
            var user = {"id": 10, "firstName": $('#firstName').val(), "lastName":       $('#lastName').val(), "age": 69, "freeText": "55555", "weight": 55};

            $.ajax({
            type: "POST",
            contentType: "application/json",
            url: "http://localhost:8080/test/webresources/entity.user/",
            dataType: "json",
            data: JSON.stringify(user),

            success: function(response) {
               $('#myModal').modal('hide');
            },
            error: function(data) {
                alert('addUser error: ');
            }
        });

    }); 

REST服務

@Stateless
@Path("entity.user")

public class UsersFacadeREST extends AbstractFacade<Users> {
@PersistenceContext(unitName = "testPU")
private EntityManager em;

public UsersFacadeREST() {
    super(Users.class);
}

@POST
@Override
@Consumes({"application/xml", "application/json"})
public void create(Users entity) {
    super.create(entity);
}

只需2美分,那么您可以定義一個Result Object,您可以在每次休息電話后返回它

Class Result{
   private String statusCode;
   private String statusDescription;

}

在豆

@POST
@Override
@Consumes({"application/xml", "application/json"})
@Produces({ "application/json"})
public Result create(Users entity) {
  Result result = new Result();
  try{
    super.create(entity);
   result.setStatus("200");
   result.setStatusDescriptions("Success");
   }catch(Exception) {
        result.setStatus("500");
        result.setStatusDescriptions("Fail");
   }

  return result;  // Return this as Json 
}

您稍后可以使用jquery解析HTML中的響應,並根據“狀態”處理流程

1)在服務器端創建自己的RESTException。

2)每當您回應該異常時; 在HTTP標頭中添加該異常消息。

3)在HTTP協議中,在服務器端使用Exceptions頭中的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部分

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM