Search code examples
angularerror-handlingrxjscombinelatest

How to have a separate error handling for each function in combineLatest?


I need to handle each function's error scenario in this combineLatest. I'll add the code below

const combined = combineLatest(
  this.myservice1.fn1(param),
  this.myservice2.fn2(), 
  this.myservice3.fn3());

const subscribe = combined.subscribe(
  ([fn1,fn2, fn3]) => {
    // operations i need to do
  },
  // how to handle error for fn1, fn2, fn3 separately
  (error) => {
  }
);

Any help would be appreciated!


Solution

  • You can catch errors for each source Observable before using combineLatest latest and eventually rethrow it if you want to handle them later or transform them to a different error:

    combineLatest(
      this.myservice1.fn1(param)
        .pipe(
          catchError(err => {
            if (err.whatever === 42) {
              // ... whatever
            }
            throw err;
          }),
        ),
      this.myservice2.fn2()
        .pipe(
          catchError(err => /* ... */),
        ),
      ...
    )