tedious
tedious copied to clipboard
Automatically try to reconnect if error in connection
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.
When the connection ends it's put in a FINAL state which cannot make a new connection. You can try two things:
- 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();
});