From 512890bb764c194b8e706011b83b3479799f1c06 Mon Sep 17 00:00:00 2001 From: Maximilian Antoni Date: Sun, 4 Aug 2013 22:02:43 +0200 Subject: [PATCH] Handle exceptions in filters --- lib/hub.js | 13 +++++++++---- test/test-addFilter.js | 28 ++++++++++++++++++++++++++++ 2 files changed, 37 insertions(+), 4 deletions(-) diff --git a/lib/hub.js b/lib/hub.js index a62afb4..62c3c85 100644 --- a/lib/hub.js +++ b/lib/hub.js @@ -134,11 +134,16 @@ function matcherIndex(arr, event) { return -1; } -function chain(filter, next) { +function chain(filter, then) { return function (scope, re, callback) { - filter.call(scope, function (cb) { - next(scope, re, cb || callback); - }, callback); + function next(cb) { + then(scope, re, cb || callback); + } + try { + filter.call(scope, next, callback); + } catch (e) { + callback(e); + } }; } diff --git a/test/test-addFilter.js b/test/test-addFilter.js index b127332..14bed28 100644 --- a/test/test-addFilter.js +++ b/test/test-addFilter.js @@ -265,6 +265,34 @@ test('hub.addFilter', { this.hub.emit('test.b'); sinon.assert.calledTwice(spy); + }, + + 'yields error if filter throws': function () { + var spy = sinon.spy(); + var err = new Error('ouch'); + this.hub.addFilter('test', function () { + throw err; + }); + + this.hub.emit('test', spy); + + sinon.assert.calledOnce(spy); + sinon.assert.calledWith(spy, err); + }, + + 'does not invoke next filter or listeners if filter throws': function () { + var filter = sinon.spy(function (next) { next(); }); + var listener = sinon.spy(); + this.hub.addFilter('test', function () { + throw new Error('ouch'); + }); + this.hub.addFilter('test', filter); + this.hub.addListener('test', listener); + + this.hub.emit('test', function () {}); + + sinon.assert.notCalled(filter); + sinon.assert.notCalled(listener); } });