From 99895aa215c5fc62c6de13fd5f73d224fa9994cc Mon Sep 17 00:00:00 2001 From: TJ Holowaychuk Date: Tue, 27 Aug 2013 20:24:04 -0700 Subject: [PATCH] change app to emit "error" events instead of app.error(fn) --- lib/application.js | 26 ++++++++------------------ lib/context.js | 11 ++++++++--- 2 files changed, 16 insertions(+), 21 deletions(-) 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) {