Examining the code below, how is it possible that the try/catch block is catching the "Route Error"? My understanding is that the callback registered to the '/' route is executed on the main event loop and as such the exception cannot be caught by the specified try/catch block because it is not part of the call stack where the callback is executed.
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');
});
});
A related question is why the following "Crash Me" error is not crashing the node app. After all the function in which this error is being thrown is running on the main event loop and should result in an uncaught exception thus crashing the app should it not? Unless the native mongo driver is catching the error and quietly snuffing it...
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');
});
});