Skip to content

Instantly share code, notes, and snippets.

@benw
Created January 25, 2010 05:33
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save benw/285654 to your computer and use it in GitHub Desktop.
Save benw/285654 to your computer and use it in GitHub Desktop.
var sys = require('sys');
var http = require('http');
var port = 3000;
http.createServer(dispatchRequest).listen(port);
sys.puts('Server running on port ' + port);
// This is the web framework, which wants to send
// a '500 Internal Server Error' to the client
// if the application using the framework
// throws an exception.
function dispatchRequest(req, res)
{
process.exceptionCatcher = function (e) {
sys.error(e.stack);
if (!res.sentHeaders) {
// 500 Internal Server Error
res.sendHeader(500, { 'Content-Type': 'text/plain'});
}
res.sendBody('Internal Server Error: '
+ e.message + '\n\n' + e.stack + '\n');
res.finish();
};
// No point calling handleRequest() in a try {} block,
// because it is async and will simply return after
// setting up some I/O callbacks.
handleRequest(req, res);
}
// This is the application using the web framework.
function handleRequest(req, res)
{
// Simple simulation of a request handler that normally
// works fine after doing some I/O (simulated by setTimeout)
// but under certain buggy conditions can throw exceptions.
setTimeout(function () {
if (req.url === '/throw-before-headers') {
throw new Error('throw-before-headers');
}
res.sendHeader(200, { 'Content-Type': 'text/plain'});
res.sentHeaders = true;
res.sendBody('Some page content.\n');
if (req.url === '/throw-after-headers') {
throw new Error('throw-after-headers');
}
res.sendBody('You requested ' + req.url + '\n');
res.finish();
}, 100);
// handleRequest returns before the callback throws any exeptions.
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment