diff --git a/lib/context.js b/lib/context.js index 058b6a7..fb98ebc 100644 --- a/lib/context.js +++ b/lib/context.js @@ -104,14 +104,18 @@ var proto = module.exports = { if (!(err instanceof Error)) err = new Error('non-error thrown: ' + err); + var headerSent = false; + if (this.headerSent || !this.writable) { + headerSent = err.headerSent = true; + } + // delegate this.app.emit('error', err, this); // nothing we can do here other // than delegate to the app-level // handler and log. - if (this.headerSent || !this.writable) { - err.headerSent = true; + if (headerSent) { return; } diff --git a/test/context/onerror.js b/test/context/onerror.js index fd5defd..94f0bc1 100644 --- a/test/context/onerror.js +++ b/test/context/onerror.js @@ -88,6 +88,29 @@ describe('ctx.onerror(err)', function(){ }) }) + it('should ignore error after headerSent', function(done){ + var app = koa(); + + app.on('error', function(err){ + err.message.should.equal('mock error'); + err.headerSent.should.equal(true); + done(); + }); + + app.use(function*() { + this.status = 200; + this.set('X-Foo', 'Bar'); + this.res.flushHeaders(); + yield Promise.reject(new Error('mock error')); + this.body = 'response'; + }); + + request(app.listen()) + .get('/') + .expect('X-Foo', 'Bar') + .expect(200, function() {}); + }) + describe('when invalid err.status', function(){ describe('not number', function(){ it('should respond 500', function(done){