Skip to content

Instantly share code, notes, and snippets.

@mde
Created February 12, 2014 22:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mde/8965696 to your computer and use it in GitHub Desktop.
Save mde/8965696 to your computer and use it in GitHub Desktop.
Thrown error in Mongo callback not caught by domain
var http = require('http')
, domain = require('domain')
, mongo = require('mongodb')
, config = {
username: null
, dbname: null
, prefix: null
, password: null
, host: 'localhost'
, port: 27017
}
, server = new mongo.Server(config.host, config.port)
, client = new mongo.MongoClient(server, config)
, _getConnectionUrl;
_getConnectionUrl = function (config) {
var connectionString = 'mongodb://';
if (config.username) {
connectionString += config.username;
if (config.password) {
connectionString += ':' + config.password;
}
connectionString += '@';
}
connectionString += config.host;
if (config.port) {
connectionString += ':' + config.port;
}
if (config.dbname) {
connectionString += '/' + config.dbname;
}
return connectionString;
};
client.connect(_getConnectionUrl(config), function (err, db) {
var collection;
if (err) {
console.log('Could not connect to Mongo.', err);
}
else {
console.log('Connected to Mongo.');
http.createServer(function (req, res) {
var dmn = domain.create();
dmn.on('error', function (err) {
console.log('Domain caught error');
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end(err.message + '\n');
});
dmn.run(function () {
setTimeout(function () {
// Domain correctly catches this
throw new Error('HELP COMPUTER');
}, 0);
/*
collection = db.collection('foos');
// This call correctly returns no error, no data
collection.findOne({id: 'asdf'}, function (err, data) {
console.log('Mongo returned:', arguments);
// Domain does not catch this
throw new Error();
});
*/
});
}).listen(1337, '127.0.0.1');
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment