Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
How to do domains...
// based on an example by @mikeal
var http = require('http')
, domain = require('domain')
;
module.exports = function (handler) {
var server = http.createServer(function (req, resp) {
var d = domain.create()
// add these to the domain
// explicitely so they dont
// get mixed into other domains
domain.add(req)
domain.add(resp)
d.run(function () {
handler(req, resp)
})
d.on('uncaughtException', function (e) {
// cleanup io, end streams
// don't cascade to the server
// or root domain
d.dispose()
d.once('dispose', function () {
// give a chance for streams
// and other things to end
// gracefully - eg. remove a half
// written file, rollback a transaction
process.exit()
})
})
d.on('error', function (err) {
console.error(err)
resp.statusCode = 500
resp.end()
if(d.listeners('error').length == 1) {
d.emit('uncaughtException', err)
}
})
})
return server
}
@mikeal

This comment has been minimized.

Copy link

commented Oct 4, 2012

@izs how important is it to call dispose() in this case?

@ritch it's not a given that you should bring down the process.

@ritch

This comment has been minimized.

Copy link
Owner Author

commented Oct 4, 2012

True, also dispose() shouldn't be a given. Updated to wrap those in an uncaughtException event.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.