Created
February 12, 2014 22:18
-
-
Save mde/8965696 to your computer and use it in GitHub Desktop.
Thrown error in Mongo callback not caught by domain
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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