diff --git a/lib/application.js b/lib/application.js index 3ba9193..8a8b35d 100644 --- a/lib/application.js +++ b/lib/application.js @@ -98,7 +98,7 @@ app.callback = function(){ return function(req, res, next){ var ctx = self.createContext(req, res); next = next || ctx.onerror; - ctx.socket.once('error', next); + ctx.onSocketError(next); co.call(ctx, gen)(next); } }; diff --git a/lib/context.js b/lib/context.js index 050ea1a..b379754 100644 --- a/lib/context.js +++ b/lib/context.js @@ -488,4 +488,20 @@ module.exports = { attachment: function() { return this.response.attachment.apply(this.response, arguments); }, + + /** + * Invoke `fn` on socket errors and + * handle cleanup on response. + * + * @param {Function} fn + * @api private + */ + + onSocketError: function(fn){ + var sock = this.socket; + sock.once('error', fn); + this.res.on('finish', function(){ + sock.removeListener('error', fn); + }); + } };