2012-05-14 91 views
2

我傾向於在我的應用程序中使用大量的jQuery Ajax調用服務器端。在jquery ajax錯誤回調中捕獲錯誤?

通常,當服務器端出現問題時,會序列化一個errormessage並將其作爲響應發送(JSON)。類似

{ "ErrorMessage" : "Something went wrong: " + ex.message } 

東西,我想知道的是,如果有什麼辦法可以使錯誤最終在jQuery的AJAX error回調,而不是success

有沒有辦法做到這一點?還是應該堅持我以前處理錯誤的方式?無論你提供一個PHP還是ASP.NET + c#示例,都沒關係,因爲我對這兩者都感興趣。謝謝

回答

3

你可以讓他們最終在error callback在jQuery上。在ASP.NET中,您只需將web.config中的custom errors部分更改爲<customErrors mode="Off" />BUT如果轉到此路由,請確保將Web服務放在單獨的文件夾中,以便您只做它爲您的Web服務調用而不關閉整個站點;例如:

<location Path="/Services"> <!--Your web service lives here --> 
    <system.web> 
     <customErrors mode="Off" /> 
    </system.web> 
</location> 

這樣一來,扔在你的web方法的任何異常都將被在jQuery中的error callback處理。

您可以讓異常傳播而不用將其緩存到Web方法中,或者您可以捕獲異常並重新拋出更「用戶友好」的消息。

+0

啊好吧,不過我想這些錯誤將作爲被退回asp.net默認錯誤頁面爲HTML而不是JSON? – Johan

+1

'request,status,error'將作爲JSON對象返回。你可以這樣做:alert(request.responseText);'在你的錯誤處理程序中。看到這裏:http://stackoverflow.com/questions/377644/jquery-ajax-error-handling-show-custom-exception-messages – Icarus

0

這是可能的使用Deferred對象在jQuery 1.5+。本·納德爾大約有一些例子,你可以看看這裏http://www.bennadel.com/blog/2255-Using-jQuery-s-Pipe-Method-To-Change-Deferred-Resolution.htm這裏http://www.bennadel.com/blog/2123-Using-Deferred-Objects-In-jQuery-1-5-To-Normalize-API-Responses.htm

下面是它的JavaScript代碼的簡化版本

var request = $.ajax({ 
    type: "post", 
    url: "./web_service.cfm", 
    dataType: "json" 
}); 

request = request.pipe(

    // Filter the SUCCESS responses from the API. 
    function (response) { 

     // real success 
     if (response.success) { 
      return (response); 
     } 
     else { 
      // The response is actually a FAIL even though it 
      // came through as a success (200). Convert this 
      // promise resolution to a FAIL. 
      return (
       $.Deferred().reject(response) 
      ); 
     } 
    }, 

    // Filter the FAIL responses from the API. 
    function (response) { 
     return ({ 
      success: false, 
      data: null, 
      errors: ["Unexpected error: " + response.status + " " + response.statusText] 
     }); 

    } 

); 


// Now that our API response has been filtered, let's attach 
// our success and fail handlers to the promise resolution. 
request.then(

    function (response) { 
     console.log("Success!!!", response); 
    }, 

    function (response) { 
     console.log("Fail!!!", response); 
    } 

);