tedious icon indicating copy to clipboard operation
tedious copied to clipboard

Automatically try to reconnect if error in connection

Open kerby82 opened this issue 4 years ago • 1 comments

I have this code:

var connection = new Connection(config);
connection.on('connect', function (err) {
    if (err) {
        console.log("Error connecting to the db", err);
        connection.close();
    } else {
        console.log('Connected to: ', config.options.database);
    }
});
connection.on('end', function(err) {
    console.log("On close called");
    connection.connect();
});
connection.connect();
module.exports = connection

I want to try reconnect if there is an error in the connection. Intercepting the end event and trying to reconnect I get the following error:

ConnectionError: .connectcan not be called on a Connection inFinal state.

kerby82 avatar Apr 28 '21 15:04 kerby82

When the connection ends it's put in a FINAL state which cannot make a new connection. You can try two things:

  1. Make a new connection
connection.on('end', function(err) {
  console.log("On close called");
  connection = new Connection(config);
  connection.connect();
  connection.on('connect', (err) => {
    if (err) {
      console.log('Connection Failed2');
      connection.close();
      return;
    }

    executeStatement();
  });
});

Or 2. Transition the existing connection state back to its INITIALIZED state:

connection.on('end', function(err) {
  console.log("On close called");
  connection.transitionTo(connection.STATE.INITIALIZED)
  connection.connect();
});

IanChokS avatar Apr 29 '21 21:04 IanChokS