diff --git a/lib/application.js b/lib/application.js index cda045c..373f884 100644 --- a/lib/application.js +++ b/lib/application.js @@ -33,6 +33,7 @@ exports = module.exports = Application; function Application() { if (!(this instanceof Application)) return new Application; this.env = process.env.NODE_ENV || 'development'; + this.on('error', this.onerror.bind(this)); this.outputErrors = 'test' != this.env; this.subdomainOffset = 2; this.poweredBy = true; @@ -119,37 +120,25 @@ app.context = function(obj){ app.callback = function(){ var mw = [respond].concat(this.middleware); var fn = compose(mw)(downstream); - var onerror = this.onerror.bind(this); var self = this; return function(req, res){ var ctx = new self.Context(self, req, res); if (!ctx.socket.listeners('error').length) { - ctx.socket.on('error', onerror); - } - - function done(err) { - if (err) ctx.onerror(err); + ctx.socket.on('error', function(err){ + self.emit('error', err); + }); } co.call(ctx, function *(){ yield fn; - }, done); + }, function(err){ + if (err) ctx.onerror(err); + }); } }; -/** - * Set the application-level error handling `fn`. - * - * @param {Function} fn - * @api public - */ - -app.error = function(fn){ - this.onerror = fn; -}; - /** * Default error handler. * @@ -169,6 +158,7 @@ function respond(next){ return function *(){ yield next; + var app = this.app; var res = this.res; var body = this.body; var head = 'HEAD' == this.method; diff --git a/lib/context.js b/lib/context.js index ea60413..33d60af 100644 --- a/lib/context.js +++ b/lib/context.js @@ -562,12 +562,17 @@ module.exports = { */ onerror: function(err){ - this.app.onerror(err); - // nothing we can do here other // than delegate to the app-level // handler and log. - if (this.headerSent) return; + if (this.headerSent) { + err.headerSent = true; + this.app.emit('error', err); + return; + } + + // delegate + this.app.emit('error', err); // err.status support if (err.status) {