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??


  • 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) {
    3. Structure your code such that your I/O is event driven:

        // 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 ',;
        // Handle errors
        socket.addEventListener('error', function (event) {
           console.log('WebSocket error observed:', event);


    • The above methods allow you to completely handle a websockets exception.

    • Regardless of whether the exception is handled or not, the Chrome debugger will tell you if an exception has occurred. This is a Good Thing. It's called a "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).

      In Microsoft's Visual Studio debugger, there's a little checkbox you can use to "gag" first chance exceptions. I'm not aware of any similar "checkbox" in Chrome debugger.


      • Chrome debugger has a "filter". EXAMPLE FILTER REGEX: ^((?!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.