how to catch Sequelize connection error

↘锁芯ラ 提交于 2020-06-25 05:37:59

问题


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.


回答1:


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);
  });



回答2:


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);

});


来源:https://stackoverflow.com/questions/38650200/how-to-catch-sequelize-connection-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!