javascriptajaxerror-handlingrxjsreactive-extensions-js

RxJS Continue Listening After Ajax Error


RxJs stops listening to click events when an inner observable errors (Ajax request). I'm trying to figure out how to keep the event listener hooked to the button click event and gracefully handle the inner ajax error.

Here is my example code and a link to plunkr

var input = $("#testBtn");
var test = Rx.Observable.fromEvent(input,'click');

var testAjax = function() {
  return Rx.Observable.range(0,3).then(function(x){ 
    if(x==2)throw "RAWR"; //Simulating a promise error.
    return x;
  });
}

test.map(function(){
  return Rx.Observable.when(testAjax());
})
.switchLatest()
.subscribe(
  function (x) {
      console.log('Next: ', x);
  },
  function (err) {
      console.log('Error: ' + err);   
  },
  function () {
      console.log('Completed');   
  });

http://plnkr.co/edit/NGMB7RkBbpN1ji4mfzih


Solution

  • You can use the catch operator (or the catchException alias) to catch and handle errors which occur in an observable, so that subscribers are not notified of the error.

    Ignore Errors:

    return Rx.Observable
        .when(testAjax())
        .catch(Rx.Observable.empty()); // continues with an empty obs after error.
    

    Handle Errors:

    var empty = Rx.Observable.return('default value');
    return Rx.Observable
        .when(testAjax())
        .catch(function (error) {
            console.log('error:', error);
            return empty;
        });