Created
March 30, 2014 22:33
-
-
Save ivanoats/9881066 to your computer and use it in GitHub Desktop.
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
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