WCF REST Service & iOS Error Processing with NSError



我有一个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 
{

在错误描述中,我只收到一条通用消息,如"操作无法完成"。

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

提前感谢您的帮助。

错误消息将出现在请求(响应体)返回的数据上:

//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
}

最新更新