Chrome JavaScript console async error handling

I have Javascript in a Chrome extension that runs every 3 seconds and tries to make a connection to a local WebSocket server.

setInterval(attemptConnection, 3000);

function attemptConnection() {

try {
    var exampleSocket = new WebSocket("ws://localhost:8080");
    exampleSocket.onmessage = function (event) {
        var JsonObject = JSON.parse(event.data);
        document.getElementById(JsonObject.elementTagValue).setAttribute("value", JsonObject.valueToSet);

    }
}

catch(err) {
//do something here
    }

      

I only plan on running my local WebSocket server at specific times. If the connection is made, the WebSocket server will send some JSON data to be used immediately by javascript.

When I go to developer tools, I see that I am getting ERR_CONNECTION_REFUSED in the console many times because there is clearly nothing in that endpoint and this is the expected behavior. Is there a way to suppress these console outputs or is there a better solution?

EDIT - Updated the code and I still get errors on the console

setInterval(attemptConnection, 3000);

function attemptConnection() {
    var exampleSocket = new WebSocket("ws://localhost:8080");
    exampleSocket.onmessage = function (event) {
        var JsonObject = JSON.parse(event.data);
        document.getElementById(JsonObject.elementTagValue).setAttribute("value", JsonObject.valueToSet);
        exampleSocket.send(event.data);

        exampleSocket.onerror = function () {
            //do nothing
        }
    }
}

      

+3


source to share


3 answers


Suppose you need to handle errors with onerror

, you have to handle onclose

. The simplest check is the error code 1000

, which means a normal socket close

exampleSocket.onclose = (event) => {
   if (event.code != 1000) {
      // "Normal closure, meaning that the purpose for which the connection was established has been fulfilled.";
   }
}

      

While the full error code handling is described here and I am posting here for your convenience:

     exampleSocket.onclose = (event) => {
        if (event.code == 1000)
            reason = "Normal closure, meaning that the purpose for which the connection was established has been fulfilled.";
        else if(event.code == 1001)
            reason = "An endpoint is \"going away\", such as a server going down or a browser having navigated away from a page.";
        else if(event.code == 1002)
            reason = "An endpoint is terminating the connection due to a protocol error";
        else if(event.code == 1003)
            reason = "An endpoint is terminating the connection because it has received a type of data it cannot accept (e.g., an endpoint that understands only text data MAY send this if it receives a binary message).";
        else if(event.code == 1004)
            reason = "Reserved. The specific meaning might be defined in the future.";
        else if(event.code == 1005)
            reason = "No status code was actually present.";
        else if(event.code == 1006)
           reason = "The connection was closed abnormally, e.g., without sending or receiving a Close control frame";
        else if(event.code == 1007)
            reason = "An endpoint is terminating the connection because it has received data within a message that was not consistent with the type of the message (e.g., non-UTF-8 [http://tools.ietf.org/html/rfc3629] data within a text message).";
        else if(event.code == 1008)
            reason = "An endpoint is terminating the connection because it has received a message that \"violates its policy\". This reason is given either if there is no other sutible reason, or if there is a need to hide specific details about the policy.";
        else if(event.code == 1009)
           reason = "An endpoint is terminating the connection because it has received a message that is too big for it to process.";
        else if(event.code == 1010) // Note that this status code is not used by the server, because it can fail the WebSocket handshake instead.
            reason = "An endpoint (client) is terminating the connection because it has expected the server to negotiate one or more extension, but the server didn't return them in the response message of the WebSocket handshake. <br /> Specifically, the extensions that are needed are: " + event.reason;
        else if(event.code == 1011)
            reason = "A server is terminating the connection because it encountered an unexpected condition that prevented it from fulfilling the request.";
        else if(event.code == 1015)
            reason = "The connection was closed due to a failure to perform a TLS handshake (e.g., the server certificate can't be verified).";
        else
            reason = "Unknown reason";
     }

      



var exampleSocket = new WebSocket("ws://localhost:8080");
    exampleSocket.onmessage = function (event) {
        var JsonObject = JSON.parse(event.data);
        console.log(JsonObject)
        exampleSocket.send(event.data);

        exampleSocket.onerror = function () {
            //do nothing
        }
    }
exampleSocket.onclose = (event) => {
            if (event.code == 1000)
                reason = "Normal closure, meaning that the purpose for which the connection was established has been fulfilled.";
            else if(event.code == 1001)
                reason = "An endpoint is \"going away\", such as a server going down or a browser having navigated away from a page.";
            else if(event.code == 1002)
                reason = "An endpoint is terminating the connection due to a protocol error";
            else if(event.code == 1003)
                reason = "An endpoint is terminating the connection because it has received a type of data it cannot accept (e.g., an endpoint that understands only text data MAY send this if it receives a binary message).";
            else if(event.code == 1004)
                reason = "Reserved. The specific meaning might be defined in the future.";
            else if(event.code == 1005)
                reason = "No status code was actually present.";
            else if(event.code == 1006)
               reason = "The connection was closed abnormally, e.g., without sending or receiving a Close control frame";
            else if(event.code == 1007)
                reason = "An endpoint is terminating the connection because it has received data within a message that was not consistent with the type of the message (e.g., non-UTF-8 [http://tools.ietf.org/html/rfc3629] data within a text message).";
            else if(event.code == 1008)
                reason = "An endpoint is terminating the connection because it has received a message that \"violates its policy\". This reason is given either if there is no other sutible reason, or if there is a need to hide specific details about the policy.";
            else if(event.code == 1009)
               reason = "An endpoint is terminating the connection because it has received a message that is too big for it to process.";
            else if(event.code == 1010) // Note that this status code is not used by the server, because it can fail the WebSocket handshake instead.
                reason = "An endpoint (client) is terminating the connection because it has expected the server to negotiate one or more extension, but the server didn't return them in the response message of the WebSocket handshake. <br /> Specifically, the extensions that are needed are: " + event.reason;
            else if(event.code == 1011)
                reason = "A server is terminating the connection because it encountered an unexpected condition that prevented it from fulfilling the request.";
            else if(event.code == 1015)
                reason = "The connection was closed due to a failure to perform a TLS handshake (e.g., the server certificate can't be verified).";
            else
                reason = "Unknown reason";
                console.error(reason);
         }
      

Run code


I've added a full WebSocket client wrapper here that also handles reconnection with autoReconnectInterval

and maxAttempts

with simple reconnection logic (porting from the official WebSocket node examples).



function WebSocketClient() {
  this.number = 0; // Message number
  this.autoReconnectInterval = 5 * 1000; // ms
  this.maxAttempts = 3;
  this.attempts = 0;
}
WebSocketClient.prototype.open = function(url) {
  var self = this;
  this.url = url;

  this.instance = new WebSocket(this.url);
  this.instance.onopen = () => {
    self.onopen();
  }
  this.instance.onmessage = (data, flags) => {
    self.number++;
    self.onmessage(data, flags, this.number);
  }
  this.instance.onclose = (e) => {
    switch (e) {
      case 1000: // CLOSE_NORMAL
        console.log("WebSocket: closed normally");
        break;
      default: // Abnormal closure
        if (self.attempts < self.maxAttempts) self.reconnect(e);
        self.attempts++;
        break;
    }
    this.onclose(e);
  }
  this.instance.onerror = (e) => {
    switch (e.code) {
      case 'ECONNREFUSED':
        self.reconnect(e);
        break;
      default:
        self.onerror(e);
        break;
    }
  }
}
WebSocketClient.prototype.send = function(data, option) {
  try {
    this.instance.send(data, option);
  } catch (e) {
    this.instance.emit('error', e);
  }
}
WebSocketClient.prototype.reconnect = function(e) {
  var self = this;

  console.log("WebSocketClient: retry in %s ms attempt %d", self.autoReconnectInterval, self.attempts);
  setTimeout(function() {
    console.log("WebSocketClient: reconnecting...");
    self.open(self.url);
  }, self.autoReconnectInterval);
}
WebSocketClient.prototype.onopen = function(e) {
  console.log("WebSocketClient: open", arguments);
}
WebSocketClient.prototype.onmessage = function(data, flags, number) {
  console.log("WebSocketClient: message", data);
}
WebSocketClient.prototype.onerror = function(e) {
  console.log("WebSocketClient: error");
}
WebSocketClient.prototype.onclose = function(e) {
  console.log("WebSocketClient: closed");
}

var wsc = new WebSocketClient();
wsc.open('wss://localhost:8080/');
wsc.onopen = function(e) {
  console.log("WebSocketClient connected:", e);
  this.send("echo");
}
wsc.onmessage = function(data, flags, number) {
  console.log("WebSocketClient message", data);
}
      

Run code


0


source


You cannot use try/catch

to catch this error because it happens asynchronously. You must use an event handler onerror

.



function attemptConnection() {
    var exampleSocket = new WebSocket("ws://localhost:8080");
    exampleSocket.onmessage = function (event) {
        var JsonObject = JSON.parse(event.data);
        document.getElementById(JsonObject.elementTagValue).setAttribute("value", JsonObject.valueToSet);

    };
    exampleSocket.onerror = function() {
        // do nothing
    };
}

      

0


source


You may be able to only log one error if you clear the timeout in your error handler. You can also trigger another timeout in your onmessage function so that it only fires when messages are received. Try

var timer = null;

function attemptConnection() {
    var exampleSocket = new WebSocket("ws://localhost:8080");

        exampleSocket.onmessage = function (event) {
        timer = setTimeout(attemptConnection, 100);
        var JsonObject = JSON.parse(event.data);
        document.getElementById(JsonObject.elementTagValue).setAttribute("value", JsonObject.valueToSet);
        exampleSocket.send(event.data);
    }
    exampleSocket.onerror = function (event) {
          console.log('error')
            //do nothin
          clearTimeout(timer)

      }
}

attemptConnection();

      

0


source







All Articles