2

问题

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: ');
            }
        });

    }); 

休息服务

@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);
}
4

2 回答 2

1

只是我的 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 中的响应并根据“状态”处理流程

于 2013-02-27T07:26:47.600 回答
0

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 部分

于 2013-02-27T07:45:26.870 回答