2013-06-25 62 views
0

我想從C#中設置自定義錯誤,而不是像現在這樣默認xhr.responseText。 如何將cSharpErrorMessage傳遞給ajax錯誤?自定義ajax錯誤來自C#

這裏是我的C#代碼:

 [WebMethod] 
     [ScriptMethod(ResponseFormat = ResponseFormat.Json)] 
     public static AjaxResult<string> GetAutoCompleteHtml(string termList) 
     { 
      const string cSharpErrorMessage = "Unable to generate autocomplete HTML."; 

      try 
      { 
       //some logic 
      } 
      catch (Exception ex) 
      { 
       //some logic 
      } 
     } 

這裏是我的ajax功能:

function StartAutoCompleteSearch(termsList) { 
    if (termsList.length > 2) { 
     $.ajax({ 
      url: '/Ajax/AjaxCalls.aspx/GetAutoCompleteHtml', 
      type: 'POST', 
      data: "{'termList':'" + termsList + "'}", 
      global: false, 
      datatype: JSON, 
      success: function(response) { 
       //some logic 
      }, 
      error: function(xhr, response) { 
       var err = eval("(" + xhr.responseText + ")"); 
       alert(err.Message + " Click OK to log back in "); 
       window.location = "/login"; 
      } 
     }); 
    } 
} 

回答

1

只是拋出一個異常。就像這樣:

throw new Exception(cSharpErrorMessage); 

實例與您的代碼:

[WebMethod] 
[ScriptMethod(ResponseFormat = ResponseFormat.Json)] 
public static AjaxResult<string> GetAutoCompleteHtml(string termList) 
{ 
     const string cSharpErrorMessage = "Unable to generate autocomplete HTML."; 

     try 
     { 
       //some logic 
     } 
     catch (Exception ex) 
     { 
       //some logic to clean up and then throw exception 
       throw new Exception(cSharpErrorMessage); 
     } 
    } 

如果需要顯示錯誤消息作爲Ajax調用的第三個參數,試試這個:

HttpContext.Current.Response.StatusCode = 500; 
HttpContext.Current.Response.StatusDescription = cSharpErrorMessage; 
HttpContext.Current.Response.End(); 

你腳本:

error: function(xhr, response,errorThrown) { 
       alert(errorThrown + " Click OK to log back in "); 
       window.location = "/login"; 
      } 
+0

呃......'errorThrown'是「unde」罰款「,當我嘗試你的解決方案。 – mtt

+1

@mtashev:對不起,應該是狀態描述。檢查我更新的答案 –

+0

仍然未定義,當我將其更改爲'StatusDescription'。由於某種原因,它永遠不會在代碼後面到達catch塊。只要有錯誤,它就會從ajax提醒我。 – mtt