Handle error in RxJs flatMap stream and continue processing

I am using RxJs in an Angular 2 application to retrieve data from an API for multiple parallel pages and save any unsuccessful retry requests in the future.

To do this, I want to catch the errors generated by flatMap-ing http get (the code below) and continue further processing the stream. In case of an error, my current solution causes the stream to be interrupted.

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());  

Say, in the above example, the HTTP request for pages 2 and 3 fails. I want to handle the error (save the failed request again later) for both of these requests and continue with the other requests and get the mapping to json ().

.onErrorResumeNext catch, .

+3
1

Observable.throw, .

, return Observable.of("Error: Foo.Bar");, .

catch Observable.empty(), .

, :

.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>
Hide result
+6

Source: https://habr.com/ru/post/1671936/


All Articles