【问题标题】:Prototype callback functions swallowing exceptions原型回调函数吞噬异常
【发布时间】:2011-02-05 18:46:44
【问题描述】:

使用原型版本 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.");
};

好的,所以问题是,如果您在 Firefox 中使用 Firebug 运行此代码,则违规行不会输出异常 - 它被吞没了。吞咽。 我知道捕获这些的唯一方法(例如,如果我正在调试)是将回调函数的内容包装在 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);
    }
};

有没有其他人遇到过这个问题?有什么解决方法吗?

提前致谢!

【问题讨论】:

    标签: javascript ajax prototypejs dhtml


    【解决方案1】:

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

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

    希望能帮助其他有相同问题的人,直到实施更持久的解决方案。

    【讨论】:

    • 我认为您引用的代码仅适用于 Ajax 事件,不适用于问题所涉及的简单 onClick 类型的事件。
    • 这是“解决方案”!您应该实现 Ajax.Responders -> onException 方法,如上所示。
    • 这太棒了,谢谢你用所有的来源很好地布置它
    猜你喜欢
    • 1970-01-01
    • 2015-11-19
    • 2016-04-23
    • 2020-08-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-24
    • 1970-01-01
    相关资源
    最近更新 更多