2016-09-23 34 views
1

我有一個C#web方法,有時會在下面顯示的調用超時(> 30秒)時拋出異常。這很好,我期待這種行爲,但問題是,當ajax調用命中.fail回調時,錯誤消息指出「內部服務器錯誤」。我希望能夠捕獲異常並報告數據庫超時。我怎樣才能做到這一點?如何在ajax調用引發異常的C#webmethod上指定消息?

[WebMethod] 
[ScriptMethod(ResponseFormat = ResponseFormat.Json)] 
public static string GetSPResults(string reportId, string sproc, Dictionary<string, string> parameters, string[] ensureArrays, string[] encryptArrays, string[] dateFields) 
{ 
    ... 
     XElement result = avdata.ExecuteSPXmlXElement(sproc, parameters, null); 
    ... 
} 

$.ajax({ 
    type: "POST", 
    url: "/Patrol/Report.aspx/GetSPResults", 
    contentType: "application/json; charset=utf-8", 
    dataType: "json", 
    data: JSON.stringify(postData) 
}).done(function (result) { 
    ... 
}).fail(function (jqXHR, textStatus, err) { 
    alert("An error has occurred: " + err); //rerpots "Internal server error" no matter what problem occurs server-side 
}); 
+0

你不能做到這一點。在這種情況下,內部服務器錯誤是來自服務器的正確響應。你可以做的是在服務器端捕獲異常並返回錯誤消息的響應,稍後在你的.done函數中,如果響應正確或錯誤,你將不得不作出反應 – MajkeloDev

+0

你是否檢查過textStatus字符串的內容?看起來它可以返回一個''timeout''值(以及''error'',''abort''和''parsererror'') – pinhead

+1

@pinhead textStatus的值爲'error',這是從服務器 - >數據庫的數據庫連接超時,而不是從客戶端 - >服務器超時,我認爲會導致'超時'返回值 –

回答

0

我用這個

 $.ajax({ 
      type: "POST", 
      url: "/Patrol/Report.aspx/GetSPResults", 
     contentType: "application/json; charset=utf-8", 
     dataType: "json", 
     data: JSON.stringify(postData) 

     error: function (jqXHR, textStatus, errorThrown) { 
      mensaje = false; 
      if (jqXHR.status === 0) { 
       alert("Not connect: Verify Network."); 
      } else if (jqXHR.status == 404) { 
       alert("Requested page not found [404]"); 
      } else if (jqXHR.status == 500) { 
       alert("Internal Server Error [500]."); 
      } else if (textStatus === 'parsererror') { 
       alert("Requested JSON parse failed."); 
      } else if (textStatus === 'timeout') { 
       alert("Time out error."); 
      } else if (textStatus === 'abort') { 
       alert("Ajax request aborted."); 
      } else { 
       toastr.error("Uncaught Error:", "Mensaje Servidor"); 
      } 
     } 
    }); 
相關問題