[RxJS] Error handling operator: catch

Most of the common RxJS operators are about transformation, combination or filtering, but this lesson is about a new category, error handling operators, and its most important operator: catch().

 

Basic catch( err => Observable):

var foo = Rx.Observable.interval(500)
  .zip(Rx.Observable.of('a','b','c','d',2), (x,y)=>y);

var bar = foo.map(x => x.toUpperCase());

/*
--a--b--c--d--2|     (foo)
map(toUpperCase)
--A--B--C--D--#      (bar)
catch(# => ###|)
--A--B--C--D--###|
*/

var result = bar.catch(error => Rx.Observable.of('###'));

result.subscribe(
  function (x) { console.log('next ' + x); },
  function (err) { console.log('error ' + err); },
  function () { console.log('done'); },
);

 

Retry with catch( (error, outputObs) => Observable):

var foo = Rx.Observable.interval(500)
  .map( () => Math.random());

var bar = foo.map(x => {
  if(x < 0.5){
    return x;
  }else{
    throw "Error, too large, try again"
  }
});

var result = bar
  .catch(
     (error, outputObs) => {
        return outputObs;
     }
  );

result.subscribe(
  function (x) { console.log('next ' + x); },
  function (err) { console.log('error ' + err); },
  function () { console.log('done'); },
);

Code check whether the x is large than 0.5, if is then throw error, if not, then continue. 

bar$ catch the error and use 'outputObs' to repeat the action, so evenytime, it hits the error, it will restart.

posted @ 2016-05-31 19:41  Zhentiw  阅读(346)  评论(0编辑  收藏  举报