原型回调函数吞噬异常

时间:2010-04-08 15:56:43

标签: 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);
    }
};

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

提前致谢!

1 个答案:

答案 0 :(得分:4)

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

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

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