Created
September 28, 2011 07:47
-
-
Save jhurliman/1247268 to your computer and use it in GitHub Desktop.
Basic error handling in Express
This file contains hidden or 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
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