从节点中的回调传播错误

时间:2015-02-01 13:03:30

标签: node.js mongodb

就节点而言,我是一个新手,所以我在这里要问的可能是愚蠢的,所以请耐心等待。

下面是连接到给定mongodb数据库的节点模块的代码,我的问题是在第19行,我试图抛出错误,以防无法建立与数据库服务器的连接或数据库服务器已关闭,但节点抱怨,请指教。

代码: -

var dbinit_func = function(db_name){
try{
// require mongoose , if it's not there
// throw an exception and but out
var mongoose = require('mongoose');
}
catch(err){
  throw "Error Mongoose Not Found"
}
try{
// connect to the db
mongoose.connect("mongodb://localhost/" + db_name);
// get a reference to the connection object
var db_connection = mongoose.connection;
// subscribe to events on the connection object
db_connection.on('error', function(err){
  // holy cow "A Connection Error", shout it out loud
  // and but out
    throw new Error(err.message);--> This is where the problem Occurs
});
// bind to the connection open event , we just need to
// do it once , so we use the once method on the
// connection object
db_connection.once('open', function(){})
}
catch(err){
  // we got an error most probably a connection error
  // so we but out from here
  throw "Connection Error";
}
}

module.exports = dbinit_func;

节点发出的消息: -

/Users/tristan625/projects/node_projs/school_web/models/db.js:19
    throw new Error(err.message);
          ^

1 个答案:

答案 0 :(得分:0)

您的代码是以同步样式编写的,如try / catch块所示。您必须了解的是,mongoose.connect函数是异步的。当你调用throw new Error()时,该调用将发生在回调中,这不在你的try / catch块的范围内,因此你不能使用它们来处理错误。

必须编写dbinit_func以允许回调

这是一种非常标准的做你正在做的事情的方式

function dbinit_func(db_name, callback) {
  var mongoose = require('mongoose');
  mongoose.connect('mongodb://localhost/ + db_name', { auto_reconnect: true });

  var db = mongoose.connection;
  db.once('error', function(err){

    //trigger callback with an error
    callback(err);
  });

  db.once('open', function() {

    //trigger callback with success
    callback(null, 'DB Connection is open');
  });

}

module.exports = dbinit_func;

// to call this function, you'd want to do something like this

var dbinit = require('/path/to/your/module');

dbinit('mydatabasename', function(err, res){
  // at this point, there will either be  an error
  if (err) console.log(err.message);

  // else it will be success
  console.log(res);

});