-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');
});
});