【问题标题】:WCF REST Service & iOS Error Handling With NSError使用 NSError 处理 WCF REST 服务和 iOS 错误
【发布时间】:2012-11-19 17:33:25
【问题描述】:

我有一个 WCF RESTful 服务,并试图勾勒出我将如何处理服务器和各种客户端上的错误。该服务可以从 Web (jQuery) 和 iOS 产品中访问。下面看看我是如何在服务上抛出错误的:

    [WebGet(UriTemplate = "get/{id}", ResponseFormat = WebMessageFormat.Json)]
    public Person Get(string id)
    {
        //check security
        if(!SecurityHelper.IsAuthenticated()) { throw new WebFaultException<PersonException>(new PersonException { Reason = "Permission denied." }, HttpStatusCode.Unauthorized); }

我可以使用 jQuery 像这样调用服务:

        $.ajax({
          type: "GET",
          dataType: "json",
          url: "/person/get/123",
          success: function(data) {
            alert('success');
          },
          error: function(xhr, status, error) {
            alert("AJAX Error!");
            alert(xhr.responseText);
          }
        });
      });

...一切正常 - 调用并抛出错误(因为我没有提供任何身份验证)并且错误:回调被调用。在检查 xhr.responseText 时的错误回调中,我得到了正确的 JSON 对象 ({"reason":"Permission denied!"}),显示了服务器提供的错误原因。

现在 - 我正在尝试将我的 iOS 应用程序放在一起以调用相同的服务,并且从那里一切都运行良好除了我无法获得由服务。这是我从 iOS 调用 REST 服务时的代码:

//set up for any errors
NSError *error = nil;

//set up response
NSURLResponse *response = [[NSURLResponse alloc] init];

//make the request
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];

//check for error
if(error)
{
    //debug
    NSLog(error.description);

    //send back error
    return error;
}
else 
{

在 error.description 中,我只收到一条通用消息,例如“无法完成操作。”

如何获取服务器发送的自定义错误信息?我一直在查看 NSError 类的 userInfo 属性,但不知道我是否可以获取自定义信息,如果可以,我该怎么做。

提前感谢您的帮助。

【问题讨论】:

    标签: jquery asp.net ios wcf rest


    【解决方案1】:

    错误消息将在请求返回的数据(响应正文)上:

    //make the request
    NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
    
    if (error) {
        if (data) {
            NSString *respBody = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
        } else {
            NSLog(@"%@", error.description);
        }
    }
    else 
    {
        // get response
    }
    

    【讨论】:

    • 是的,刚刚检查过,确实如此。非常感谢...我很感激。
    猜你喜欢
    • 2012-05-13
    • 2017-02-28
    • 1970-01-01
    • 2015-01-14
    • 1970-01-01
    • 1970-01-01
    • 2014-01-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多