From 45e6659ae38c300e0b8fcf79d87255aa475a6939 Mon Sep 17 00:00:00 2001 From: Konstantin Vyatkin Date: Thu, 17 Oct 2019 12:32:38 -0400 Subject: [PATCH 1/2] remove `error-inject` and fix error handling --- lib/response.js | 11 ++++++----- package.json | 1 - 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/lib/response.js b/lib/response.js index 87ecc56a9..e5af66f73 100644 --- a/lib/response.js +++ b/lib/response.js @@ -6,7 +6,6 @@ */ const contentDisposition = require('content-disposition'); -const ensureErrorHandler = require('error-inject'); const getType = require('cache-content-type'); const onFinish = require('on-finished'); const escape = require('escape-html'); @@ -166,12 +165,14 @@ module.exports = { } // stream - if ('function' == typeof val.pipe) { + if (val instanceof Stream) { onFinish(this.res, destroy.bind(null, val)); - ensureErrorHandler(val, err => this.ctx.onerror(err)); - // overwriting - if (null != original && original != val) this.remove('Content-Length'); + if (original != val) { + val.once('error', err => this.ctx.onerror(err)); + // overwriting + if (null != original) this.remove('Content-Length'); + } if (setType) this.type = 'bin'; return; diff --git a/package.json b/package.json index 2067aaeb9..b2c7b561a 100644 --- a/package.json +++ b/package.json @@ -32,7 +32,6 @@ "depd": "^1.1.2", "destroy": "^1.0.4", "encodeurl": "^1.0.2", - "error-inject": "^1.0.0", "escape-html": "^1.0.3", "fresh": "~0.5.2", "http-assert": "^1.3.0", From 3921003d11721f6761433a6dcb7d3a055329ae4c Mon Sep 17 00:00:00 2001 From: Konstantin Vyatkin Date: Thu, 30 Apr 2020 10:48:14 -0400 Subject: [PATCH 2/2] add failing test --- test/response/body.js | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/test/response/body.js b/test/response/body.js index 1dfcac55e..9d5d57d9b 100644 --- a/test/response/body.js +++ b/test/response/body.js @@ -4,6 +4,7 @@ const response = require('../helpers/context').response; const assert = require('assert'); const fs = require('fs'); +const Stream = require('stream'); describe('res.body=', () => { describe('when Content-Type is set', () => { @@ -108,6 +109,16 @@ describe('res.body=', () => { res.body = fs.createReadStream('LICENSE'); assert.equal('application/octet-stream', res.header['content-type']); }); + + it('should add error handler to the stream, but only once', () => { + const res = response(); + const body = new Stream.PassThrough(); + assert.strictEqual(body.listenerCount('error'), 0); + res.body = body; + assert.strictEqual(body.listenerCount('error'), 1); + res.body = body; + assert.strictEqual(body.listenerCount('error'), 1); + }); }); describe('when a buffer is given', () => {