Consider following codes:
mongoose.connect('MyDatabaseURL');
var sch_obj = {field1: String};
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function() {
var model_obj = db.model('SchemaName', sch_obj);
var obj = new model_obj({field1:'MyValue'});
obj.save(function(err,data){
if(err)
console.log('error occurred:' + err); // <=== Case 1
else
console.log('saved');
});
});
/* ---------------------------------- */
mongoose.connect('MyDatabaseURL');
var sch_obj = {field1: String};
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function() {
var model_obj = db.model('SchemaName', sch_obj);
var obj = new model_obj({field1:'MyValue'});
obj.save(function(err,data){
try {
console.log('saved');
}
catch(err) // <=== Case 2
{
console.log('error occurred:' + err);
}
});
});
Question: Are they same? If yes which one is the good way to handle error?
No, they are not the same. Mongoose newer throws errors, so you’ll newer catch one. It’s why you can’t use
try ... catch ...statement to handle mongoose errors.So, the only right way is:
The reason behind it is that
throwterminates the current process unless it caught. So, most nodejs modules (e.g.express,mongoose, etc.) passes their errors using callback instead of throwing them, its a common practice in nodejs.