Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
  • Loading branch information
Elergy committed May 2, 2014
1 parent acdeaf6 commit 9aecd60
Show file tree
Hide file tree
Showing 2 changed files with 62 additions and 4 deletions.
39 changes: 35 additions & 4 deletions lib/mediator.js
Original file line number Diff line number Diff line change
Expand Up @@ -200,7 +200,8 @@
y = this._subscribers.length,
called = false,
subscriber, l,
subsBefore,subsAfter;
subsBefore,subsAfter,
predicateResult;

// Priority is preserved in the _subscribers index.
for(x, y; x < y; x++) {
Expand All @@ -209,13 +210,27 @@
if(!this.stopped){
subscriber = this._subscribers[x];
if(subscriber.options !== undefined && typeof subscriber.options.predicate === "function"){
if(subscriber.options.predicate.apply(subscriber.context, data)){
subscriber.fn.apply(subscriber.context, data);
try {
predicateResult = subscriber.options.predicate.apply(subscriber.context, data);
} catch (ex) {
predicateResult = false;
this._processException(ex);
}
if(predicateResult){
try {
subscriber.fn.apply(subscriber.context, data);
} catch(ex) {
this._processException(ex);
}
called = true;
}
}else{
subsBefore = this._subscribers.length;
subscriber.fn.apply(subscriber.context, data);
try {
subscriber.fn.apply(subscriber.context, data);
} catch(ex) {
this._processException(ex);
}
subsAfter = this._subscribers.length;
y = subsAfter;
if (subsAfter === subsBefore - 1){
Expand All @@ -241,6 +256,22 @@
}

this.stopped = false;
},

//Throw an exception in another context through setImmediate of setTimeout.
//If neither setImmediate nor setTimeout is defined we log exception's stack to the console (if it is defined)
_processException: function(ex) {
if (typeof setImmediate === 'function') {
setImmediate(function() {
throw ex;
});
} else if (typeof setTimeout === 'function') {
setTimeout(function() {
throw ex;
}, 0);
} else if (typeof console !== "undefined" && console.log) {
console.log(ex.stack);
}
}
};

Expand Down
27 changes: 27 additions & 0 deletions test/ChannelSpec.js
Original file line number Diff line number Diff line change
Expand Up @@ -299,5 +299,32 @@ describe("Channel", function() {
expect(this.a).to.equal("0123");
});

it("should call subscribers and continue running, if one of subscribers throws an exception", function(){
var sub1 = function(){
this.a += "1";
},
sub2 = function(){
this.a += "2";
throw new Error('error');
this.a += "444";
},
sub3 = function(){
this.a += "3";
},
data = ["data"];
this.a = "0";

channel.addSubscriber(sub1, {}, this);
channel.addSubscriber(sub2, {}, this);
channel.addSubscriber(sub3, {}, this);
try {
channel.publish(data);
this.a += "4";
} catch(ex) {
this.a += "555";
}
expect(this.a).to.equal("01234");
});

});
});

0 comments on commit 9aecd60

Please sign in to comment.