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.
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.
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.