zoukankan      html  css  js  c++  java
  • [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.

  • 相关阅读:
    好久没更新
    基于slick grid做infinite scroll(2)
    基于slick grid做infinite scroll(1)
    用REST访问ALM的Servlet
    Angularjs中provider,factory和service的不同
    粗糙版斗破苍穹网络阅读器
    将斗破苍穹按章分隔
    实战第一个云程序
    js变量提升
    Thread
  • 原文地址:https://www.cnblogs.com/Answer1215/p/5547170.html
Copyright © 2011-2022 走看看