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

Why there is no error thrown with Strophe.js?

本文关键字:出错 错误 Strophe js 为什么      更新时间:2023-09-26

示例代码:

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吞下了错误。更糟糕的是;抛出错误后,回调函数不会像它应该的那样返回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));

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

  • stropheh .js - log函数-默认不包含任何内容-我添加了调用我的服务器端日志服务的级别=== ERROR和级别=== FATAL
  • stropheh .js - run函数-错误的默认行为是删除处理程序并重新抛出错误-因为我已经记录了错误服务器端,我不重新抛出错误并决定保留处理程序(即使它失败了)。这种行为可能有意义(或没有意义),这取决于您自己的实现——因为我使用自定义消息,并且有一个相当复杂的消息处理例程,我不希望客户机仅仅因为消息在发送时没有正确格式化而停止,所以我想保留处理程序,无论错误与否。我用result = true;
  • 替换运行函数内的throw e行。
  • Strope.js _hitError -正如我提到的,我不希望客户端永远断开连接,所以我重写了默认行为,永远不断开连接(无论错误计数器有多高)

希望这些想法对其他人有帮助,如果你有问题或想了解更多细节,请留下评论。

我有一个类似的问题,我使用tsds上面给出的方法修复了这个问题。然而,与最小的修改。我创建了两个连接方法,一个为connect,另一个为connect_bak

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

在我的connectHandler函数和connect函数。

相关文章: