[英]Handling the data portion of a jQuery AJAX call to WCF REST service
[英]WCF REST Service & iOS Error Handling 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對象({“原因”:“權限被拒絕!”}),顯示了服務器提供的錯誤原因。
現在-我正在嘗試將我的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屬性,但無法弄清楚我是否可以獲取自定義信息,如果可以的話,我該如何去做。
在此先感謝您的幫助。
錯誤消息將出現在請求(響應主體)返回的數據上:
//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
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.