catchError

signature: catchError(project : function): Observable

Gracefully handle errors in an observable sequence.


:warning: Remember to return an observable from the catchError function!


Examples

( example tests )

Example 1: Catching error from observable

( jsBin | jsFiddle )

import { _throw } from 'rxjs/observable/throw';
import { of } from 'rxjs/observable/of';
import { catchError } from 'rxjs/operators';
//emit error
const source = _throw('This is an error!');
//gracefully handle error, returning observable with error message
const example = source.pipe(catchError(val => of(`I caught: ${val}`)));
//output: 'I caught: This is an error'
const subscribe = example.subscribe(val => console.log(val));
Example 2: Catching rejected promise

( jsBin | jsFiddle )

import { timer } from 'rxjs/observable/timer';
import { fromPromise } from 'rxjs/observable/fromPromise';
import { of } from 'rxjs/observable/of';
import { mergeMap, catchError } from 'rxjs/operators';

//create promise that immediately rejects
const myBadPromise = () =>
  new Promise((resolve, reject) => reject('Rejected!'));
//emit single value after 1 second
const source = timer(1000);
//catch rejected promise, returning observable containing error message
const example = source.pipe(
  mergeMap(_ =>
    fromPromise(myBadPromise()).pipe(
      catchError(error => of(`Bad Promise: ${error}`))
    )
  )
);
//output: 'Bad Promise: Rejected'
const subscribe = example.subscribe(val => console.log(val));

Additional Resources


:file_folder: Source Code: https://github.com/ReactiveX/rxjs/blob/master/src/internal/operators/catchError.ts

results matching ""

    No results matching ""