How to handle MySQLStore connection error?

289 Views Asked by At

I'm using NodeJS with express. I'm store the sessions to a MySQLStore (express-mysql-session) My question is how can i handle connection error? When it can't connect i want to render a page to the users instead of the "Error: connect ECONNREFUSED 127.0.0.1:3306 at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1137:16) ....." message.

My code:

const MySQLStore = require('express-mysql-session')(session);
(....)
app.use(session({
  secret: 'something',
  resave: false,
  saveUninitialized: false,
  store: new MySQLStore({
    host: something,
    user: something,
    password: something,
    database: something
  }),
  cookie: {
    maxAge: 7 * 24 * 60 * 60 * 1000
  }
}));

With the simple mysqljs i could do it easily because when i use connection.query there is an (error, result) => { ... } where i can handle error but at this MySQLStore i have no clue how to handle connection error.

1

There are 1 best solutions below

0
On

Solved it, an Express error handler middleware can catch this error too. Just paste this by the end of the application just before app.listen.

app.use((error, req, res, next) => {
  res.status(error.status || 500).render('error', { 
    msg: 'Please check back later!'
  });
});

Be aware that the next parameter needed even if we don't use it because error-handling functions have four parameters in express. If you delete it, it will not work.