Search code examples
angularerror-handlingrxjsrxjs-pipeable-operators

Why isn't this throwError being caught in catchError?


I am trying to create a pipeable operator and throw when particular conditions not met.. I am unable to throw and catch the error however.

This is my pipeable:

// My custom pipeable
export function waitFor<T>(thisToComplete$: Observable<any>) {
  return (beforeRunningThis$: Observable<T>) => {
    return new Observable<T>(observer =>
      thisToComplete$.pipe(first()).subscribe(x => {
        if (x !== 'Success') {
          console.log('Non success result encountered');
          return throwError('Rando IO Error');
        }
        return beforeRunningThis$.subscribe(observer);
      })
    );
  }
}

And consuming code:

const preReq$ = timer(1000);
const dataReq$ = getData();

try {
  dataReq$
    .pipe(waitFor(preReq$), catchError(x => {
      console.log('Code here reached');
      return of('Error was handled either here')
    }))
    .subscribe(x => console.log(`I have result ${x.toString()}`));
} catch (e) {
  console.log('Error was handled here');
}

None of the above consoles log however.

Here is a stackblitz


Solution

  • Since you are using the Observable construct observer.error is how you throw

        if (x !== 'Success') {
          console.log('Non success result encountered');
          observer.error('Rando IO Error');
        }