I'm new to express + node.js, so I'm written an rest api using mongoose. What's the best way to handle runtime errors as database errors etc.?
I've read in the express documentation that you can have a middleware function(err, res, req, next) to handle this errors, and you can call this function only calling next(err). That's ok, so Imagine you have a User moongose model and in a controller you write this function:
const find = (email, password) => {
User.find({ email: email }, (err, doc) => {
if (err) {
// handle error
}
return doc;
});
};
Then, you have in another file a handler for a route:
router.get('/users', (req, res) => {
userController.find(req.body.email);
});
So, at this point, you can handle the mongo error writing throw(err) in the model and using try/catch in the controller to then call next(err) right? But I've read that using try/catch in JavaScript is not a good practice because it creates a new execution context etc.
What's the best way to handle this errors in Express?
I will suggest you to use promises. It not only makes your code cleaner but also error handling is much easier. For reference you can visit this or this.
If you are using mongoose you can plugin your own library of promise.
const mongoose = require('mongoose');
mongoose.connect(uri);
// plug in the promise library:
mongoose.Promise = global.Promise;
mongoose.connection.on('error', (err) => {
console.error(`Mongoose connection error: ${err}`)
process.exit(1)
})
And use it like below:
In controller:
const find = (email) => {
var userQuery = User.find({ email: email });
return userQuery.exec();
};
In Router:
router.get('/users', (req, res) => {
userController.find(req.body.email).then(function(docs){
// Send your response
}).then(null, function(err){
//Handle Error
});
});