代码之家  ›  专栏  ›  技术社区  ›  Ciaran Archer

原型回调函数忽略异常

  •  5
  • Ciaran Archer  · 技术社区  · 14 年前

    使用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);
        }
    };
    

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

    事先谢谢!

    1 回复  |  直到 12 年前
        1
  •  4
  •   Ciaran Archer    14 年前

    从今天起,这就是众所周知的行为:

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

    希望这能帮助其他人解决同样的问题,直到一个更持久的解决方案得到实施。