feat: set err.headerSent before app error event emit (#923)

cherry-pick from https://github.com/koajs/koa/pull/919
This commit is contained in:
fengmk2 2017-03-02 17:30:33 +08:00 committed by Yiyu He
parent 188feafdf0
commit 8c1c69f260
2 changed files with 29 additions and 2 deletions

View file

@ -104,14 +104,18 @@ var proto = module.exports = {
if (!(err instanceof Error)) err = new Error('non-error thrown: ' + err); if (!(err instanceof Error)) err = new Error('non-error thrown: ' + err);
var headerSent = false;
if (this.headerSent || !this.writable) {
headerSent = err.headerSent = true;
}
// delegate // delegate
this.app.emit('error', err, this); this.app.emit('error', err, this);
// 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 || !this.writable) { if (headerSent) {
err.headerSent = true;
return; return;
} }

View file

@ -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('when invalid err.status', function(){
describe('not number', function(){ describe('not number', function(){
it('should respond 500', function(done){ it('should respond 500', function(done){