考虑以下代码:
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);
}
});
});
问题:它们是一样的吗?如果是,哪一种是处理错误的好方法?