I am new to Rx, and I would really appreciate a little help with error handling. I have the following code, which is basically a typeahead:
var observable = Rx.Observable.fromEvent(searchField, 'keyup')
.map(ev => ev.target.value)
.filter(text => text.length > 2)
.debounce(500 /* ms */)
.distinctUntilChanged()
.flatMapLatest(getAsyncSearchResults);
observable.subscribe(function(value) {
console.log("onNext");
throw "error"; // THIS TERMINATES THE OBSERVABLE
},
function(error) {
console.log("Error");
},
function() {
console.log("Completed");
});
The Observable terminates after an exception occurs in onNext function. This seems an unwanted behavior to me, since I don't want to wrap all of my onNext code inside a try-catch. Is there any way that I could tell the observable to keep issuing notification no matter what exception occurs?
That is the behavior of Rx on every platform, and the only way to catch exceptions in observers is ... well ... to catch them.
You could create your own
subscribeSafe
method which wraps a callback in try/catch if you often have this need.Alternatively if you can move the part(s) which are throwing from the observer to the stream itself, then you can control the error flow, and (for instance) retry.
Example below: