【问题标题】:How can I throw an exception out of an AJAX call and out of a function?如何从 AJAX 调用和函数中抛出异常?
【发布时间】:2013-07-17 23:54:57
【问题描述】:


假设我在函数中有这个 jQuery AJAX 调用:

function callPageMethod(methodName, parameters) {
    var pagePath = window.location.href;

    $.ajax({
        type: "POST",
        url: pagePath + "/" + methodName,
        contentType: "application/json; charset=utf-8",
        data: parameters,
        dataType: "json",
        success: function (response) {
            alert("ajax successful!");
        },
        error: function (response) {

            // this line is not working!
            throw response.responseText;
        }
    });
} // end of function


...我在 Visual Studio 2010 中收到此错误:

Microsoft JScript runtime error: Exception thrown and not caught.


似乎这个问题与 Visual Studio 无关,但特定于 javascript。

例如,我可以在调用$.ajax之前在这个函数中声明一个变量,在error:中赋值,然后在$.ajax调用之后将throw从函数中之后问题...



那么如何以这种方式从嵌套函数中抛出错误呢?如果可能的话,我想在这个函数之外 catch 这个错误。

【问题讨论】:

  • 你将无法在函数之外捕获它 - ajax 是异步的。只需返回 ajax 调用的结果(一个 jQuery 延迟对象),并利用 jQuery 的延迟方法
  • 有时来自 XMLHttpRequest 的安全错误会避开该请求/周围代码中的错误处理程序。

标签: javascript jquery exception-handling scope


【解决方案1】:


所以,这里有一些我发现的可能的解决方案:


   1 -- 分配一个具有error 值的变量,并在 $.ajax电话:

function callPageMethod(methodName, parameters) {
    var errorValue = null;

    $.ajax({
        ...
        ...
        ...
        error: function (response) {
            errorValue = response.responseText;
        }
    });

    if (errorValue != null) {
        throw errorValue;
    }
}


2 -- 使$.ajax 调用同步

function callPageMethod(methodName, parameters) {
    var errorValue = null;

    $.ajax({
        ...
        ...
        ...
        async: false,
        error: function (response) {

            // now it works:
            throw response.responseText;
        }
    });
}

【讨论】:

  • 解决方案 2 不再起作用,我收到一个未捕获的错误
猜你喜欢
  • 2017-08-13
  • 2016-10-12
  • 1970-01-01
  • 2020-04-06
  • 1970-01-01
  • 2011-10-24
  • 1970-01-01
  • 2016-03-20
  • 1970-01-01
相关资源
最近更新 更多