2013-08-20 55 views
-1

檢查下面的代碼,try/catch塊如何捕獲「路由錯誤」?我的理解是,註冊到'/'路由的回調函數在主事件循環中執行,因此它不會被指定的try/catch塊捕獲,因爲它不是執行回調的調用堆棧的一部分。Express,節點錯誤控制流程

var express = require('express') ; 
var app = express(); 
var http = require('http'); 

var mongod = require('mongodb'); 

var server_conf = new mongod.Server('localhost', 27017, {auto_reconnect:true}); 

//dummy logger 
var logger = { 
    error:function(message, object) {console.log('anything')}, 
    log:function(message, object) {console.log('anything')}, 
    debug:function(message, object) {console.log('anything')}} 

var db_container = {db: new mongod.Db('test', server_conf, 
    {w:1, 
     journal:true, native_parser:true, logger: logger})} 

app.use(express.bodyParser()); 
app.use(app.router); 

db_container.db.open(function(err, index_info){ 

    if(err) throw err; 
    var testcol = db_container.db.collection('testcol'); 
    try{ 
     app.get('/', function(request, res){ 
      throw new Error("Route Error"); 
      testcol.insert({hello:"moto"}, function(err,doc){ 

       if(err){ 
        throw err; 
       } 
       testcol.find({}).toArray(function(err,docs){ 
        res.send(docs); 
       }); 
      }); 

     }); 
    } 
    catch(e){ 
     res.send("err caught "+ e); 
    } 
    http.createServer(app).listen(3000, function() { 
     console.log('Express server listening on port ' + '3000'); 
    }); 
}); 

一個相關的問題是爲什麼下面的「崩潰我」錯誤不會崩潰的節點應用程序。在所有引發此錯誤的函數都在主事件循環中運行之後,應該會導致未捕獲的異常,從而導致應用程序崩潰?除非本地蒙戈驅動程序捕獲錯誤並悄悄扼殺它...

var express = require('express') ; 
var app = express(); 
var http = require('http'); 

var mongod = require('mongodb'); 

var server_conf = new mongod.Server('localhost', 27017, {auto_reconnect:true}); 

//dummy logger 
var logger = { 
    error:function(message, object) {console.log('anything')}, 
    log:function(message, object) {console.log('anything')}, 
    debug:function(message, object) {console.log('anything')}} 

var db_container = {db: new mongod.Db('test', server_conf, 
    {w:1, 
     journal:true, native_parser:true, logger: logger})} 

app.use(express.bodyParser()); 
app.use(app.router); 

db_container.db.open(function(err, index_info){ 

    if(err) throw err; 
    var testcol = db_container.db.collection('testcol'); 
    try{ 
     app.get('/', function(request, res){ 

      testcol.insert({hello:"moto"}, function(err,doc){ 
       throw new Error("Crash Me"); 

       if(err){ 
        throw err; 
       } 
       testcol.find({}).toArray(function(err,docs){ 
        res.send(docs); 
       }); 
      }); 

     }); 
    } 
    catch(e){ 
     res.send("err caught "+ e); 
    } 
    http.createServer(app).listen(3000, function() { 
     console.log('Express server listening on port ' + '3000'); 
    }); 
}); 

回答

0

的問題的第一部分答案是here

至於第二部分,這個問題仍然開放,但我相信這是由於在node-mongodb-native中的一些嘗試捕獲,從而悄悄地忽略拋出的異常。

您可以在節點上找到任何關聯的回覆-mongodb-native組here