jquery AJAX调用web方法没有运行错误函数

时间:2014-10-02 21:59:19

标签: javascript c# jquery asp.net ajax

我在一个aspx页面上有一个WebMethod,我在jquery中调用它,我试图让它在弹出框中显示抛出异常的消息,但不是在错误函数下运行代码,而是调试器停止说"异常未由用户"处理。如何将错误返回给客户端?

    [WebMethod]
    [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
    public static void SubmitSections(string item)
    {
        try
        {
            throw new Exception("Hello");
        }

        catch (Exception ex)
        {
            HttpContext.Current.Response.Write(ex.Message);
            throw new Exception(ex.Message, ex.InnerException);
        }
    }

在我的js文件中:

$.ajax({
    type: "POST",
    url: loc + "/SubmitSections",
    data: dataValue,
    contentType: 'application/json; charset=utf-8',
    dataType: 'json',
    success: function (Result) {
        $("#modal-submitting").modal('hide');
        document.location = nextPage;
    },
    error: function (XMLHttpRequest, textStatus, errorThrown) {
        $("#modal-submitting").modal('hide');
        alert("Request: " + XMLHttpRequest.toString() + "\n\nStatus: " + textStatus + "\n\nError: " + errorThrown);
    }
});//ajax call end

2 个答案:

答案 0 :(得分:0)

您应该返回一个错误,例如Http状态代码500,在客户端处理为错误。

服务器端的抛出错误没有返回给客户端。

对于WebMethod,您应该设置Response.StatusCode。

HttpContext.Current.Response.StatusCode = 500; 

答案 1 :(得分:0)

我认为您的问题是您正在从客户端脚本发出JSON请求,但是您的catch块只是将文本写入响应,而不是JSON,因此客户端错误函数不会触发。

尝试使用Newtonsoft.Json等库将.NET类转换为JSON响应。然后,您可以创建一些简单的包装类来表示响应数据,例如: -

[Serializable]
public class ResponseCustomer
{
    public int ID;
    public string CustomerName;
}

[Serializable]
public class ResponseError
{
    public int ErrorCode;
    public string ErrorMessage;
}

并在你的拦截块中......

var json = JsonConvert.SerializeObject(new ResponseError 
                                           { 
                                              ErrorCode = 500, 
                                              ErrorMessage = "oh no !" 
                                           });
context.Response.Write(json);

顺便说一句: throw new Exception(...)不建议使用,因为您将丢失堆栈跟踪,这对调试或日志记录没有帮助。如果需要重新抛出异常,建议的做法是只调用throw;(无参数)。