一种阻止 WebSocket 错误显示在浏览器控制台中的方法

A way to stop WebSocket errors to show up in browser's console

所以问题是当我尝试向远程主机启动一个新的 WebSocket 时,有时浏览器的控制台会打印一条红色错误消息并抱怨连接被拒绝,消息如下:

Error in connection establishment: net::ERR_CONNECTION_REFUSED

有错误是可以的,因为远程主机有时可能没有响应,但我无法处理这个错误消息这一事实非常烦人。

在我的 JavaScript 代码中初始化之前,是否有任何方法可以处理此错误消息或检查远程主机是否接受 WebSocket 连接??

想到了几种可能性:

  1. 添加 WebSocket.onerror错误处理程序

    myWebSocket.onerror = myEventHandler;
    
  2. 将您的 "connect" 包裹在 try/catch block

    try {
       const connection = new WebSocket(myUrl);
       ...
    }
    catch(error) {
       console.error(error);
    }
    
  3. 构建您的代码,使您的 I/O 是事件驱动的:

    https://developer.mozilla.org/en-US/docs/Web/API/WebSocket#Examples

    // Create WebSocket connection.
    const socket = new WebSocket('ws://localhost:8080');

    // Connection opened
    socket.addEventListener('open', function (event) {
        socket.send('Hello Server!');
    });

    // Listen for messages
    socket.addEventListener('message', function (event) {
       console.log('Message from server ', event.data);
    });

    // Handle errors
    socket.addEventListener('error', function (event) {
       console.log('WebSocket error observed:', event);
    });

附录:

  • 以上方法可以让你彻底处理一个websockets异常

  • 无论是否处理异常,Chrome调试器都会告诉您是否发生了异常。这是一件好事。它被称为 "First-Chance Exception":

    https://docs.microsoft.com/en-us/security-risk-detection/concepts/first-chance-exception

    .. it is known a “first chance” exception – the debugger is given the first chance of inspecting the exception prior to the application handling it (or not).

    在 Microsoft 的 Visual Studio 调试器中,有一个小复选框可用于 "gag" 第一次机会异常。我不知道 Chrome 调试器中有任何类似的 "checkbox"。

  • 可能的建议:

    • Chrome 调试器有一个 "filter"。过滤器正则表达式示例:^((?!ERR_CONNECTION_REFUSED).)*$

    • This link suggests you might be able to use the filter to "Hide Network Messages" (I haven't tried it myself). See also this link.