From f71fdfdf353172d1418a1690ae5493c52692d57d Mon Sep 17 00:00:00 2001 From: Jacob Heun Date: Mon, 12 Nov 2018 15:43:32 +0100 Subject: [PATCH] feat: conditionally emit errors test: add tests for emit override --- src/index.js | 18 ++++++++++++++++++ test/create.spec.js | 21 +++++++++++++++++++++ 2 files changed, 39 insertions(+) diff --git a/src/index.js b/src/index.js index 40ec5f4563..00a9e6e51f 100644 --- a/src/index.js +++ b/src/index.js @@ -51,7 +51,10 @@ class Node extends EventEmitter { this._transport = [] // Transport instances/references this._discovery = [] // Discovery service instances/references + // create the switch, and listen for errors this._switch = new Switch(this.peerInfo, this.peerBook, _options.switch) + this._switch.on('error', (...args) => this.emit('error', ...args)) + this.stats = this._switch.stats this.connectionManager = new ConnectionManager(this, _options.connectionManager) @@ -162,6 +165,21 @@ class Node extends EventEmitter { }) } + /** + * Overrides EventEmitter.emit to conditionally emit errors + * if there is a handler. If not, errors will be logged. + * @param {string} eventName + * @param {...any} args + * @returns {void} + */ + emit (eventName, ...args) { + if (eventName === 'error' && !this._events.error) { + log.error(...args) + } else { + super.emit(eventName, ...args) + } + } + /** * Starts the libp2p node and all sub services * diff --git a/test/create.spec.js b/test/create.spec.js index 17b1d52d4c..e832771fe5 100644 --- a/test/create.spec.js +++ b/test/create.spec.js @@ -80,4 +80,25 @@ describe('libp2p creation', () => { done() }) }) + + it('should not throw errors from switch if node has no error listeners', (done) => { + createNode([], {}, (err, node) => { + expect(err).to.not.exist() + + node._switch.emit('error', new Error('bad things')) + done() + }) + }) + + it('should emit errors from switch if node has error listeners', (done) => { + const error = new Error('bad things') + createNode([], {}, (err, node) => { + expect(err).to.not.exist() + node.once('error', (err) => { + expect(err).to.eql(error) + done() + }) + node._switch.emit('error', error) + }) + }) })