Created
October 4, 2012 14:38
-
-
Save ritch/3833934 to your computer and use it in GitHub Desktop.
How to do domains...
This file contains 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
// 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 | |
} |
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
@izs how important is it to call dispose() in this case?
@ritch it's not a given that you should bring down the process.