检查下面的代码,try/catch 块怎么可能捕获“路由错误”?我的理解是注册到“/”路由的回调在主事件循环上执行,因此指定的 try/catch 块无法捕获异常,因为它不是执行回调的调用堆栈的一部分。
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');
});
});
一个相关的问题是为什么以下“Crash Me”错误不会导致节点应用程序崩溃。毕竟抛出此错误的所有函数都在主事件循环上运行,并且应该导致未捕获的异常,从而使应用程序崩溃,不是吗?除非本机 mongo 驱动程序捕捉到错误并悄悄地扼杀它......
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');
});
});