W3cubDocs

/RxJS

catchError

function stable

Catches errors on the observable to be handled by returning a new observable or throwing an error.

catchError<T, O extends ObservableInput<any>>(selector: (err: any, caught: Observable<T>) => O): OperatorFunction<T, T | ObservedValueOf<O>>

Parameters

selector

a function that takes as arguments err, which is the error, and caught, which is the source observable, in case you'd like to "retry" that observable by returning it again. Whatever observable is returned by the selector will be used to continue the observable chain.

Returns

OperatorFunction<T, T | ObservedValueOf<O>>: An observable that originates from either the source or the observable returned by the catch selector function.

Description

catch marble diagram

Examples

Continues with a different Observable when there's an error

import { of } from 'rxjs';
import { map, catchError } from 'rxjs/operators';

of(1, 2, 3, 4, 5).pipe(
    map(n => {
  	   if (n === 4) {
	       throw 'four!';
      }
     return n;
    }),
    catchError(err => of('I', 'II', 'III', 'IV', 'V')),
  )
  .subscribe(x => console.log(x));
  // 1, 2, 3, I, II, III, IV, V

Retries the caught source Observable again in case of error, similar to retry() operator

import { of } from 'rxjs';
import { map, catchError, take } from 'rxjs/operators';

of(1, 2, 3, 4, 5).pipe(
    map(n => {
  	   if (n === 4) {
  	     throw 'four!';
      }
	     return n;
    }),
    catchError((err, caught) => caught),
    take(30),
  )
  .subscribe(x => console.log(x));
  // 1, 2, 3, 1, 2, 3, ...

Throws a new error when the source Observable throws an error

import { of } from 'rxjs';
import { map, catchError } from 'rxjs/operators';

of(1, 2, 3, 4, 5).pipe(
    map(n => {
      if (n === 4) {
        throw 'four!';
      }
      return n;
    }),
    catchError(err => {
      throw 'error in source. Details: ' + err;
    }),
  )
  .subscribe(
    x => console.log(x),
    err => console.log(err)
  );
  // 1, 2, 3, error in source. Details: four!

© 2015–2018 Google, Inc., Netflix, Inc., Microsoft Corp. and contributors.
Code licensed under an Apache-2.0 License. Documentation licensed under CC BY 4.0.
https://rxjs.dev/api/operators/catchError