Using Domains With Express
Setting up express to use the new node.js domains can be a bit tricky, but this little snippet will do the trick:
var app = express.createServer();
// a bunch of your middleware...
app.use(setupDomains);
// the rest of your middleware...
var domain = require('domain');
function setupDomains(req, res, next) {
var reqd = domain.create();
domain.active = reqd;
reqd.add(req);
reqd.add(res);
reqd.on('error', function(err) {
req.next(err);
});
res.on('end', function() {
console.log('disposing domain for url ' + req.url);
reqd.dispose();
});
reqd.run(next);
}
This way if anything throws an error that was called from an express route, but wasn't part of the same callstack, the error will return to the error handler for that route, instead of tearing down the entire process.
There are two caveats.
The first is that it appears to break if you use setupDomains prior to sessions.
The second is to be aware that if any io, such as file or database connectors, is set up and attached to the request, it will be disposed with the request and everything will go to hell. So be sure to use a separate domain when opening any io that will last longer than the request.
Written by Adam Blackburn
Related protips
4 Responses
This is pretty useful. Thanks!
Also.. according to this.. domain.dispose is being deprecated: https://github.com/joyent/node/issues/5018
And according to the domain docs, you should kill the process when an error is caught: http://nodejs.org/api/domain.html#domain_domain
Not from there, but looks like they came to a similar conclusion.
How exactly would you "use a separate domain when opening any io that will last longer than the request." ?