Skip to content

Instantly share code, notes, and snippets.

@jhurliman
Created September 28, 2011 07:47
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 jhurliman/1247268 to your computer and use it in GitHub Desktop.
Save jhurliman/1247268 to your computer and use it in GitHub Desktop.
Basic error handling in Express
app.configure(function() {
// Setup a socket error handler for all requests
app.use(socketErrorHandler);
// Catch any attempts to call res.send multiple times for the same client
app.use(onlyOneResponse);
});
function socketErrorHandler(req, res, next) {
// Check if this socket is being reused and already has an error handler
if (!req.socket.listeners('error').length) {
// Install an error handler for this socket
req.socket.addListener('error', function(err) {
console.warn('Socket error from client ' + req.socket.remoteAddress +
': ' + err);
});
}
next();
}
function onlyOneResponse(req, res, next) {
var send = res.send;
// Proxy the send method
res.send = function(body) {
if (res._doSend) {
// send has already been called
var err = new Error('Response already sent');
console.error(err.toString());
return;
}
res._doSend = send;
res._doSend(body);
};
next();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment