Mastering Reactive JavaScript
上QQ阅读APP看书,第一时间看更新

Acting when an error occurs

In the previous sections, we saw how to encapsulate an error on bacon.js. Now, we will use the OnError() method to take an action whenever this happens. This method has the same signature as that of the onValue() method and works similarly, but only for bacon errors. Now with this method, we can change the code we used in the previous section to print an error when it occurs. This is shown as follows:

var myCustomEventStream = Bacon.fromBinder(function(push){ 
push('some value');
push('other value');
push(new Bacon.Error('NOW AN ERROR HAPPENED'));
push('Now the stream will finish');
push(new Bacon.End());
});
myCustomEventStream
.onError((value)=>
console.log(value)
);

It will print the following:

    NOW AN ERROR HAPPENED
As you might expect, the OnError() method also returns a function to unsubscribe.