处理RxJs flatMap流中的错误并继续处理 [英] Handle Error in RxJs flatMap stream and continue processing

查看:124
本文介绍了处理RxJs flatMap流中的错误并继续处理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Angular 2应用程序中使用 RxJs 从API获取多页数据同时保存所有失败的请求以供将来重试.

I am using RxJs in an Angular 2 application to fetch data from an API for multiple pages in parallel and save any failed requests for future re-try.

为此,我想捕获flatMap-ing

To do so, I want to catch errors generated by flatMap-ing http get requests (code below) and continue with further stream processing. In case of error, my current solution causes stream to discontinue.

Rx.Observable.range(1, 5)
   .flatMap(pageNo => {
              params.set('page', ''+pageNo);
              return this.http.get(this.API_GET, params)
                        .catch( (err) => {
                                  //save request
                                  return Rx.Observable.throw(new Error('http failed')); 
                          });
    })
    .map((res) => res.json());  

让我们在上面的示例中说,第2页和第3页的HTTP请求失败.我要为这两个请求处理错误(保存失败的请求以后重试),并让其他请求继续并映射到json().

Let's say in above example, HTTP request for page 2 and 3 fails. I want to handle error (save failed request later retry) for both these request and let other requests continue and get mapped to json().

我尝试使用.onErrorResumeNext代替catch,但是无法完成这项工作.

I tried using .onErrorResumeNext instead of catch, but I am unable to make this work.

推荐答案

在您的捕获中,不要返回Observable.throw,则它应根据需要继续播放流.

Inside your catch, don't return an Observable.throw, then it should continue the stream as desired.

如果要将信息传播到外部流,则可以使用return Observable.of("Error: Foo.Bar");.

If you want to propagate the information to the outer stream, you could use an return Observable.of("Error: Foo.Bar"); for example.

或将错误记录在catch内部,并返回Observable.empty()以使外部流基本上忽略该错误.

Or log the error inside the catch and return an Observable.empty() to have the outer stream basically ignore the error.

换句话说,只需将其链接:

In other words, just chain this:

.catch(error => Rx.Observable.of(error));

const stream$ = Rx.Observable.range(1, 5)
    .flatMap(num => {
      return simulateRest(num)
             .catch(error => {
                 console.error(error);
                 return Rx.Observable.empty();
             });
      });
             
stream$.subscribe(console.log);

// mocking-fn for simulating an error
function simulateRest(num) {
    if (num === 2) {
        return Rx.Observable.throw("Error for request: " + num);
    }
  
    return Rx.Observable.of("Result: " + num);
}

<script src="https://unpkg.com/rxjs/bundles/Rx.min.js"></script>

这篇关于处理RxJs flatMap流中的错误并继续处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆