javascripterror-handlingwebsocketbrowser-console

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


So the problem is when I try to initiate a new WebSocket to a remote host, sometimes the browser's console prints a red error message and complains about a refused connection, here is the message:

Error in connection establishment: net::ERR_CONNECTION_REFUSED

Having an error is fine since the remote host might be not responding sometimes, but the fact that I cannot handle this error message is very annoying.

Is there any way to either handle this error message or check whether the remote host accepts the WebSocket connection before initializing one in my JavaScript code??


Solution

  • Several possibilities come to mind:

    1. Add a WebSocket.onerror error handler

      myWebSocket.onerror = myEventHandler;
      
    2. Wrap your "connect" in a try/catch block

      try {
         const connection = new WebSocket(myUrl);
         ...
      }
      catch(error) {
         console.error(error);
      }
      
    3. Structure your code such that your I/O is event driven:

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

    ADDENDUM: