add err.status support. Closes #20

This commit is contained in:
TJ Holowaychuk 2013-08-21 19:47:56 -07:00
parent f32c3540f4
commit 2de010ca47
3 changed files with 45 additions and 5 deletions

View file

@ -125,7 +125,7 @@ app.callback = function(){
var ctx = new self.Context(self, req, res); var ctx = new self.Context(self, req, res);
function done(err) { function done(err) {
if (err) ctx.error(err); if (err) ctx.onerror(err);
} }
co.call(ctx, function *(){ co.call(ctx, function *(){
@ -134,6 +134,17 @@ app.callback = function(){
} }
}; };
/**
* Default error handler.
*
* @param {Error} err
* @api private
*/
app.onerror = function(err){
if (this.outputErrors) console.error(err.stack);
};
/** /**
* Response middleware. * Response middleware.
*/ */

View file

@ -545,10 +545,20 @@ module.exports = {
* @api private * @api private
*/ */
error: function(err){ onerror: function(err){
if (this.app.outputErrors) console.error(err.stack); // nothing we can do here other
// TODO: change name // than delegate to the app-level
// TODO: header sent check // handler and log.
if (this.headerSent) return this.app.onerror(err);
// err.status support
if (err.status) {
this.status = err.status;
this.res.end(http.STATUS_CODES[err.status]);
return;
}
// respond
this.status = 500; this.status = 500;
this.res.end('Internal Server Error'); this.res.end('Internal Server Error');
}, },

View file

@ -205,6 +205,25 @@ describe('app.respond', function(){
}) })
describe('when an error occurs', function(){ describe('when an error occurs', function(){
describe('with a .status property', function(){
it('should respond with .status', function(done){
var app = koa();
app.use(function(next){
return function *(){
var err = new Error('s3 explodes');
err.status = 403;
throw err;
}
});
request(app.listen())
.get('/')
.expect(403, 'Forbidden')
.end(done);
})
})
it('should respond with 500', function(done){ it('should respond with 500', function(done){
var app = koa(); var app = koa();