change app to emit "error" events instead of app.error(fn)

master
TJ Holowaychuk 2013-08-27 20:24:04 -07:00
parent 750748834e
commit 99895aa215
2 changed files with 16 additions and 21 deletions

View File

@ -33,6 +33,7 @@ exports = module.exports = Application;
function Application() { function Application() {
if (!(this instanceof Application)) return new Application; if (!(this instanceof Application)) return new Application;
this.env = process.env.NODE_ENV || 'development'; this.env = process.env.NODE_ENV || 'development';
this.on('error', this.onerror.bind(this));
this.outputErrors = 'test' != this.env; this.outputErrors = 'test' != this.env;
this.subdomainOffset = 2; this.subdomainOffset = 2;
this.poweredBy = true; this.poweredBy = true;
@ -119,37 +120,25 @@ app.context = function(obj){
app.callback = function(){ app.callback = function(){
var mw = [respond].concat(this.middleware); var mw = [respond].concat(this.middleware);
var fn = compose(mw)(downstream); var fn = compose(mw)(downstream);
var onerror = this.onerror.bind(this);
var self = this; var self = this;
return function(req, res){ return function(req, res){
var ctx = new self.Context(self, req, res); var ctx = new self.Context(self, req, res);
if (!ctx.socket.listeners('error').length) { if (!ctx.socket.listeners('error').length) {
ctx.socket.on('error', onerror); ctx.socket.on('error', function(err){
} self.emit('error', err);
});
function done(err) {
if (err) ctx.onerror(err);
} }
co.call(ctx, function *(){ co.call(ctx, function *(){
yield fn; 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. * Default error handler.
* *
@ -169,6 +158,7 @@ function respond(next){
return function *(){ return function *(){
yield next; yield next;
var app = this.app;
var res = this.res; var res = this.res;
var body = this.body; var body = this.body;
var head = 'HEAD' == this.method; var head = 'HEAD' == this.method;

View File

@ -562,12 +562,17 @@ module.exports = {
*/ */
onerror: function(err){ onerror: function(err){
this.app.onerror(err);
// nothing we can do here other // nothing we can do here other
// than delegate to the app-level // than delegate to the app-level
// handler and log. // 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 // err.status support
if (err.status) { if (err.status) {