From 17ef9ee8293cd6b952ec335b03eb642b6ad9692f Mon Sep 17 00:00:00 2001 From: Jacob Heun Date: Tue, 4 Dec 2018 16:59:58 +0100 Subject: [PATCH] fix: conditionally emit errors from muxer (#84) * fix: conditionally emit errors from muxer * test: add test for conditional emitter License: MIT Signed-off-by: Jacob Heun --- .gitignore | 1 + package.json | 7 ++++--- src/muxer.js | 19 +++++++++++++++++++ test/muxer.spec.js | 8 ++++++++ 4 files changed, 32 insertions(+), 3 deletions(-) diff --git a/.gitignore b/.gitignore index f8690b5..9497173 100644 --- a/.gitignore +++ b/.gitignore @@ -2,6 +2,7 @@ **/*.log test/repo-tests* **/bundle.js +docs # Logs logs diff --git a/package.json b/package.json index 28b30d3..750f1bf 100644 --- a/package.json +++ b/package.json @@ -39,14 +39,14 @@ "npm": ">=3.0.0" }, "devDependencies": { - "aegir": "^17.0.1", + "aegir": "^17.1.1", "chai": "^4.2.0", "chai-checkmark": "^1.0.1", "dirty-chai": "^2.0.1", "interface-stream-muxer": "~0.6.0", "libp2p-tcp": "~0.13.0", "libp2p-websockets": "~0.12.0", - "multiaddr": "^5.0.0", + "multiaddr": "^6.0.0", "pull-file": "^1.1.0", "pull-pair": "^1.1.0", "run-parallel": "^1.1.9", @@ -55,7 +55,8 @@ "tape": "^4.9.0" }, "dependencies": { - "interface-connection": "~0.3.2", + "debug": "^4.1.0", + "interface-connection": "~0.3.3", "pull-catch": "^1.0.0", "pull-stream": "^3.6.9", "pull-stream-to-stream": "^1.3.4", diff --git a/src/muxer.js b/src/muxer.js index bb67af4..fbe233c 100644 --- a/src/muxer.js +++ b/src/muxer.js @@ -6,6 +6,9 @@ const toPull = require('stream-to-pull-stream') const pullCatch = require('pull-catch') const pull = require('pull-stream') const noop = () => {} +const debug = require('debug') +const log = debug('spdy') +log.error = debug('spdy:error') function catchError (stream) { return { @@ -57,6 +60,22 @@ module.exports = class Muxer extends EventEmitter { }) } + /** + * Conditionally emit errors if we have listeners. All other + * events are sent to EventEmitter.emit + * + * @param {string} eventName + * @param {...any} args + * @returns {void} + */ + emit (eventName, ...args) { + if (eventName === 'error' && !this._events.error) { + log.error('error', ...args) + } else { + super.emit(eventName, ...args) + } + } + // method added to enable pure stream muxer feeling newStream (callback) { if (!callback) { diff --git a/test/muxer.spec.js b/test/muxer.spec.js index 6bb3929..c94f554 100644 --- a/test/muxer.spec.js +++ b/test/muxer.spec.js @@ -100,4 +100,12 @@ describe('multiplex-muxer', () => { code: 'ERR_UNKNOWN' })) }) + + it('should not throw if there are no error listeners', () => { + muxer.removeAllListeners('error') + + muxer.spdy.emit('error', Object.assign(new Error('bad things'), { + code: 'ERR_UNKNOWN' + })) + }) })