Angular 12/Typescript/rxjs: error handling of nested Promises and rxjs Observable

Viewed 511

I have a mix of nested Promises and subscriptions, and I simple want to do the following:

  • Call my function bar() and understand if it was fully successfully, or if an error occurred

current approach: Currently my bar() returns a boolean Observable, and I handle each error separately, for Promise via .catch, for the rxjs Observable via the error handle:

    foo(): void {
       this.bar.subscribe((data: boolean) => console.log('the function call bar() was ' + data));
    }

    bar(): Observable<boolean> {
    let subject = new Subject<boolean>();
    
        this.httpHandler.newFoo().subscribe(
        (data) => 
          this.bar(data)
            .then((barData) => 
              this.httpHandler.updateBar().subscribe(
                (barData2) => subject.next(true),
                (error) => subject.next(false)))
            .catch(err => subject.next(false)),
        (error) => subject.next(false));

        return subject.asObservable();
    }

Apparently this is messy, and looks like an overkill for the simple purpose to understand if the bar() function call finished without any errors. Is there a better way to handle nested errors altogether?

Thanks in advance

1 Answers

I think this could be succinctly written as:

this.httpHandler.newFoo().pipe(
  switchMap(data =>
    from(this.bar(data)).pipe(
      switchMap(() =>
        this.httpHandler.updateBar().pipe(
          mapTo(true)
        )
      )
    )
  ),
  catchError(() => of(false))
)

To make an observable out of a promise, use from(). Use switchMap() to transition between observables. Then it's just a matter of chaining your calls:

this.httpHandler.newFoo() -> this.bar() -> this.httpHandler.updateBar()

and returning true in the end, otherwise false for any error.

Related