Reputation:
One reads this article here from MDN on how to use promises.
I clearly check for errors in my database query but should I also be using catch
after then
when I use the database?
Database
const pool = mysql.createPool(helper.getMySQL());
const queryMaker = (query) => {
return new Promise ((resolve, reject) => {
pool.query(query, (error, results, fields) => {
error ? reject(error) : resolve(results, fields);
});
});
};
exports.selectAllDomains = () => {
const query = `some mysql query`;
return queryMaker(query);
};
Use Case
router.route('/items').get((req, res) => {
MySQL.selectAllDomains().then((results) => {
if(req.user){
results[results.length] = req.user;
}
res.status(200).json(results);
});
// Should I have a catch here?
});
Upvotes: 1
Views: 65
Reputation: 707926
Should I have a catch in this promise code?
Yes, you should. If your database call reject its promise, then you never respond to the http request which will just sit there with no response getting sent and will eventually time out. In addition to failing to send a response to the client in a timely fashion, this also consumes a server resource for the duration of the timeout. If there's some temporary database failure, this can potentially cause a lot of requests to pile up until they timeout which could exhaust resources on the server.
Instead, you need to catch the error and immediately return an error response to the http request.
router.route('/items').get((req, res) => {
MySQL.selectAllDomains().then((results) => {
if(req.user){
results[results.length] = req.user;
}
res.status(200).json(results);
}).catch(err => {
console.log(err);
res.status(500).send("database internal error");
});
});
If I were to guess, I'd say no because I'm not doing something error prone in the then method.
It is not safe to assume that there will never be an error from your DB calls. Robust programming anticipates that there could be an error there in some conditions (disk error, database disk volume offline, connection pool problem, query error, etc...) and handles that error appropriately.
Upvotes: 1
Reputation: 429
When there is a DB error the promise will return an error and this error will not enter into the then callback that you have. So since you are handling an HTTP request if there is a DB error then the client will not receive a response and will eventually timeout.
I suggest that you do use a catch because then if there is a DB error you can send a proper error message to the client with something like res.status(500).send(error);
Upvotes: 1