码迷,mamicode.com
首页 > Web开发 > 详细

[RxJS] Error handling operator: catch

时间:2016-05-31 20:42:58      阅读:137      评论:0      收藏:0      [点我收藏+]

标签:

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.

[RxJS] Error handling operator: catch

标签:

原文地址:http://www.cnblogs.com/Answer1215/p/5547170.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!