Javascript 为什么Strophe.js没有抛出错误?

Javascript 为什么Strophe.js没有抛出错误?,javascript,strophe,Javascript,Strophe,示例代码: var connection = null; function onConnect(status) { im_a_big_error.log('wtf'); // Why it doesn't throw me an error here ??

示例代码:

var connection = null;

function onConnect(status) {
    im_a_big_error.log('wtf');
    // Why it doesn't throw me an error here ??                                                                                                                                                                                                
}

$().ready(function() {
    connection = new Strophe.Connection('http://localhost:8080/http-bind');
    connection.connect('admin@localhost', 'admin', onConnect);
});
它不会让我的Chrome控制台出错


您有办法解决此问题吗?

是的,Strophe经常自己捕获错误,目前不提供任何获取连接错误信息的功能。虽然错误捕获是可以的,但是自己捕获错误的可能性不是很好。但您可以使用以下代码修复它:

$().ready(function() {
    connection = new Strophe.Connection('http://localhost:8080/http-bind');
    connection._hitError = function (reqStatus) {
        this.errors++;
        Strophe.warn("request errored, status: " + reqStatus + ", 
                number of errors: " + this.errors);
        if (this.errors > 4) this._onDisconnectTimeout();
        myErrorHandler(reqStatus, this.errors);
    };
    connection.connect('admin@localhost', 'admin', onConnect);
});

其中
myErrorHandler
是您的自定义连接错误处理程序

我使用Strophe已经有一段时间了,我不得不修改它的默认错误处理例程以满足我们的需要

  • Strophe.js-
    log
    函数-默认情况下不包含任何内容-我为服务器端日志服务添加了对level===ERROR和level===FATAL的调用
  • Strophe.js-
    run
    函数-错误的默认行为是删除处理程序并重新显示错误-因为我已经记录了错误服务器端,所以我不会重新显示错误,并决定保留处理程序(即使失败)。这种行为可能有意义(或没有意义),这取决于您自己的实现——因为我使用自定义消息,并且有一个相当复杂的消息处理例程,我不希望客户端因为消息发送时未正确格式化而停止,所以我想保留处理程序,不管是否出错。我用
    result=true替换run函数内的throw e行
  • Strope.js
    \u hitError
    -如我所述,我不希望客户端断开连接,因此我将默认行为重写为从不断开连接(无论错误计数器有多高)

希望这些想法能对其他人有所帮助-如果你有问题/需要详细信息,请留下评论。

是的,strophe会吞下错误。更糟的抛出错误后,回调将不会像应该的那样返回true,strophe将删除处理程序。一旦发生错误,将不再调用回调

我发现当前答案中的代码有点难以使用。在内部,我们为每个回调使用以下包装器

function callback(cb) {
// Callback wrapper with
// (1) proper error reporting (Strophe swallows errors)
// (2) always returns true to keep the handler installed
return function() {
    try {
        cb.apply(this, arguments);
    } catch (e){
        console.log('ERROR: ' + (e.stack ? e.stack : e));
    }

    // Return true to keep calling the callback.
    return true;
};
}
该包装器将在问题代码中使用,如下所示:

connection.connect('admin@localhost', 'admin', callback(onConnect));

我有一个类似的问题,我用上面tsds给出的方法修复了这个问题。然而,只要稍作修改。我创建了两个连接方法,一个是connect,另一个是connect\u bak我放置了脚本

this.connection._hitError=function (reqStatus) {
client.connect_bak();
};

在我的connectHandler函数和connect函数中。使函数始终绑定在connect上。

是否调用了
onConnect
?它应该抛出
undefined不是函数
或类似函数。
connection.connect('admin@localhost'和'admin',onConnect)在此调用,
$()。ready(..)
在空jQuery集合上注册
ready
事件。您应该使用
$(document).ready(..)
或其较短的等价物
$(..)-
是您的回调函数。谢谢您的回答。使用
$(document.ready(..)
不会抛出错误:(我很抱歉;此代码的早期版本有一个错误,如果调用回调时包含多个参数,则会损坏参数。如果您使用了旧代码,请进行修改。我认为应该是连接。_proto。_hitError,因为_hitError是一种Bosh方法。可能这在2.5年前的回答后发生了变化。