[RxJS] Error handling operator: catch
Posted Answer1215
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[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.
以上是关于[RxJS] Error handling operator: catch的主要内容,如果未能解决你的问题,请参考以下文章
[RxJS] Error handling operator: catch
[RxJS] Handling Multiple Streams with Merge
[RxJS] Handling a Complete Stream with Reduce