如何在ajax调用C#webmethod上指定抛出异常的消息?

时间:2016-09-23 15:12:41

标签: javascript c# jquery ajax webmethod

我有一个C#网络方法,当下面显示的调用超时(> 30秒)时,有时会抛出异常。这很好我期待这种行为,但问题是,当ajax调用命中.fail回调时,错误消息指出“内部服务器错误”。我希望能够捕获异常并报告数据库超时。我怎么能这样做?

[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
});

1 个答案:

答案 0 :(得分: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");
            }
        }
    });