javascript - 原型(prototype)回调函数吞噬异常

标签 javascript ajax prototypejs dhtml

使用原型(prototype)版本 1.6.0.2。

我有一个常见的问题,即异常在回调函数中被抛出时被吞没,通常是在我尝试处理对 Ajax.Request 调用的响应时。这是一个简单的例子:

HTML 标记:

<input type="button" id="myButton" value="Press Me" />

Javascript:

MYSITE = {};

document.observe("dom:loaded", function () {

    // Set up our helper object
    MYSITE.pageHelper = new MYSITE.PageHelper();

});


MYSITE.PageHelper = function() {

    console.log("PageHelper called.");

    $("myButton").observe("click", this.makeCall.bindAsEventListener(this));

};

MYSITE.PageHelper.prototype.makeCall = function() {

    console.log("Make call.");

    new Ajax.Request(
            "remoteCall.cfm", 
            {
                method: 'get', 
                parameters: "", 
                onComplete: this.handleCallback.bindAsEventListener(this)

            });


};

MYSITE.PageHelper.prototype.handleCallback = function(resp) {

    console.log("Start callback processing...");

    var x = missingVar + "text"; // This line generates an exception...

    console.log("Finished callback processing.");
};

好的,所以问题是,如果您在带有 Firebug 的 Firefox 中运行此代码,将不会为有问题的行输出异常 - 它被吞没了。囫囵吞枣。 我知道捕捉这些的唯一方法(比如我正在调试)是将回调函数的内容包装在 try/catch 中。例如:

MYSITE.PageHelper.prototype.handleCallback = function(resp) {

    try {

        console.log("Start callback processing...");

        var x = missingVar + "text"; // This line generates an exception...

        console.log("Finished callback processing.");

    } catch (e) {
        console.log(e);
    }
};

有没有人遇到过这个问题?那里有任何解决方法吗?

提前致谢!

最佳答案

截至今天,这是已知行为:

http://groups.google.com/group/prototype-scriptaculous/browse_thread/thread/e71c7a6bfb656380/7d1c8a23edc07f03?lnk=gst&q=exception+swallowed#

这里有一张增强处理这些被吞噬的异常的票:

https://prototype.lighthouseapp.com/projects/8886/tickets/634-no-exception-on-error-in-oncreate-method-of-ajaxrequest

建议的一种解决方法是添加以下代码(感谢 Glenn Maynard!):

Ajax.Responders.register({ 
        onException: function(request, exception) { 
                (function() { throw exception; }).defer(); 
        } 
});

希望在实现更永久的解决方案之前帮助其他人解决同样的问题。

关于javascript - 原型(prototype)回调函数吞噬异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2601411/

相关文章:

javascript - React Native SafeAreaView 背景颜色 - 如何为屏幕顶部和底部分配两种不同的背景颜色?

javascript - Rails Edge Guides,AJAX 示例 - 为什么同时使用 'format.js' 和 'format.json' ?

javascript - 如何直接在 Ajax 成功结果上从 JSON 对象加载数据表?

javascript - 如何使用 JavaScript 打开文件?

jquery - 在 jQuery 中调用 `click()` 是否只触发 jQuery 附加事件?

javascript - Swiper.js 分页自定义项目符号不会点击移动到下一张幻灯片

JavaScript - 使用字符串原型(prototype)函数做错事

javascript - 如何使元素在 selenium webdriver 中可见?

javascript - 如何将多列数据渲染到一列中?

javascript - 无法访问 Class.create 中的 'this' 中的 'each'