如何使用REST服务处理客户端 - 服务器应用程序中的错误?

时间:2013-02-27 06:56:40

标签: java jquery ajax rest exception-handling

问题

1)如何在使用REST服务时处理客户端 - 服务器应用程序中的错误?有人可以帮助我使用示例代码在下面的代码中处理错误消息的最佳方法是什么。例如,如果在create-service的情况下如何捕获客户端和/或服务器端的异常?

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 个答案:

答案 0 :(得分:1)

只需2美分 那么你可以定义一个结果对象,你可以在每次休息之后返回

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中解析响应,并根据'status'处理流程

答案 1 :(得分:0)

1)在服务器端创建自己的RESTException。

2)每当你回应那个例外时;在HTTP标头中添加该异常消息。

3)在HTTP协议中使用errorCode&amp;&amp;您的标头中可用的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 Exception Handling part-1
Spring MVC REST Exception Handling part-2