Home > OS >  How to throw an error to parent catchError?
How to throw an error to parent catchError?

Time:11-16

Simulation of my code: I have a method load(), which makes a request to get an id. After that, I need to approve this id by approveId() method, which makes some post request. In case of successful approve id, I need to log it. If id isn't approved, I need to retry getId request and approve it. If id isn't approved after retrying - log to the console a message that approve was failed.

load() {
    this.httpService.getId().pipe(
      switchMap((id: string) => this.approveId(id)),
      tap(() => {
        // some successful operations
        console.log('Success got ID');
      }),
      retry(1),
      catchError(() => {
        console.error('Approve was failed');

        return of(null);
      })
    )
  }
approveId(id: string) {
    this.httpService.approveId(id).pipe(
      first(),
      tap(() => {
        console.log('Success approved');
      }),
      catchError((error) => {
        // ???

        return of(null);
      })
    )
  }

In this case, let's suppose that this.httpService.getId() always returns a valid id. retry(1) operator should be called in case of an error in approve request, so what can be done in approveId's catchError operator to throw an error to outer retry and on repeat error to outer catchError

CodePudding user response:

Just rethrow the error as an error notification with throwError() from catchError():

import { catchError, throwError } from 'rxjs';

...

catchError((error) => {
  // ???

  return throwError(error);
})
  • Related