Skip to content

Instantly share code, notes, and snippets.

@ivanoats
Created March 30, 2014 22:33
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 ivanoats/9881066 to your computer and use it in GitHub Desktop.
Save ivanoats/9881066 to your computer and use it in GitHub Desktop.
var http = require("http"),
domain = require("domain"),
server = http.createServer(),
counter = 0;
server.on("request", function (req, res) {
// this domain will cover this entire request/response cycle
var d = domain.create();
d.on("error", function (err) {
// outputs all relevant context for this error
console.error("Error:", err);
res.writeHead(500, { "content-type": "text/plain" });
res.end(err.message);
// stops the server from accepting new connections/requests
console.warn("closing server to new connections");
server.close(function () {
console.warn("terminating process");
process.exit(1);
});
});
// adding the req and res objects to the domain allows
// errors they encounter to be handled by the domain
// automatically
d.add(req);
d.add(res);
d.run(function () {
if (++counter === 4) {
throw new Error("Unexpected Error");
}
res.writeHead(200, { "content-type": "text/plain" });
res.end("Hello World\n");
});
});
server.listen(3000);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment