Zhen Liu
Zhen Liu

Reputation: 7932

how to catch Sequelize connection error

How to catch a sequelize connection error in case there is one?

I tried to do

var connection = new Sequelize("db://uri");
connection.on("error", function() { /* perhaps reconnect here */ });

but apparently this is not supported.

I wanted to do this because I think sequelize might be throwing an occasional unhandled ETIMEOUT and crashing my node process.

Currently I am using sequelize to connect a mysql instance. I only need it for like 2-3 hours and during that time I will be doing a many read queries. The mysql server will not be connected to anything else during that time.

Upvotes: 7

Views: 28139

Answers (4)

Ahmad Malik
Ahmad Malik

Reputation: 161

Same answer just using async/await

try {
  await sequelize.authenticate()
} catch (err) {
  console.error('Unable to connect to the database:', err)
}

Upvotes: 0

Joshua Pchumba
Joshua Pchumba

Reputation: 111

Using sequelize sync method provides an easy way to catch the error. The then block handles a Successful connection and the catch handles the rejection.To get a detailed reason for a failure access the error object. example: error.message e.t.c Hope this helps.

   sequelize.sync().
then(function() {
  console.log('DB connection sucessful.');
}).catch(err=> console.log('error has occured'));

Upvotes: 0

Mustafa Alammar
Mustafa Alammar

Reputation: 656

Using sync() for this is considerably dangerous when using external migrations or when database integrity is paramount (when isn't it!)

The more up-to-date way of doing this is to use authenticate()

sequelize
  .authenticate()
  .then(() => {
    console.log('Connection has been established successfully.');
  })
  .catch(err => {
    console.error('Unable to connect to the database:', err);
  });

Upvotes: 17

Aman Gupta
Aman Gupta

Reputation: 3797

Use sequelize sync for that

var Sequelize = require('sequelize');

sequelize = new Sequelize(config.database, config.username, config.password, {
    'host' : config.host,
    'dialect' : config.dialect,
    'port' : config.port,
    'logging' : false
  })

sequelize.sync().then(function(){
  console.log('DB connection sucessful.');
}, function(err){
  // catch error here
  console.log(err);

});

Upvotes: -1

Related Questions