本文介绍了如何捕获“WebSocket 连接到 'ws://xxx:nn' 失败:在收到握手响应之前关闭连接"错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个以端口 nn 启动的节点服务器,并且上面没有任何 WebSocket 服务.

Let's say I have a node server started with port nn, and there is not any WebSocket service on it.

问题是我的客户端尝试将 WebSocket 服务连接到该服务器.

And the problem is that my client trys to connect a WebSocket service to this server.

显然,它应该无法连接到服务器.

Obviously, it should fail to connect to the server.

但是我没能发现这个错误,我的客户端代码如下:

But I couldn't catch this error, my client code is the following:

try {
    this.ws = new WebSocket('ws://xxx:nn');
} catch ( e ) {
    fallback();
    console.warn(e);
}

我的期望是 fallback 方法在连接失败时被调用,但实际上错误没有被上面的 try...catch

My expectation is that the fallback method gets called while connecting fails, but actually the error is not caught by the above try...catch

有谁知道如何在我的用例中捕获错误?

Does anyone know how to catch the error in my usecase?

推荐答案

可以注册websocket对象的onError回调

You can register for onError callback of websocket object

exampleSocket.onerror=function(event){
    console.log("Error");
}

您可以参考以下示例.http://jsfiddle.net/g28yuymv/1/

捕获错误示例http://jsfiddle.net/g28yuymv/4/

这篇关于如何捕获“WebSocket 连接到 'ws://xxx:nn' 失败:在收到握手响应之前关闭连接"错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-22 15:08