From faeaff5c149a81a188ab8e5af0b994029e45acbb Mon Sep 17 00:00:00 2001 From: Konstantin Vyatkin Date: Sat, 16 May 2020 04:40:34 -0400 Subject: [PATCH] fox: remove `error-inject` and fix error handling (#1409) --- lib/response.js | 12 ++++++------ package.json | 1 - test/response/body.js | 11 +++++++++++ 3 files changed, 17 insertions(+), 7 deletions(-) diff --git a/lib/response.js b/lib/response.js index a7841c3d6..d14e86a11 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'); @@ -167,12 +166,13 @@ 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 3091b9e9d..5fdeb5364 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", 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', () => {