2016-09-23 33 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"); 
      } 
     } 
    }); 
相关问题