catchError

signature: catchError(project : function): Observable

Gracefully handle errors in an observable sequence.


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


catchError - 图2

Examples

(
example tests
)

Example 1: Catching error from observable

( jsBin |
jsFiddle )

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

( jsBin |
jsFiddle )

  1. import { timer } from 'rxjs/observable/timer';
  2. import { fromPromise } from 'rxjs/observable/timer';
  3. import { of } from 'rxjs/observable/of';
  4. import { mergeMap, catchError } from 'rxjs/operators';
  5. //create promise that immediately rejects
  6. const myBadPromise = () =>
  7. new Promise((resolve, reject) => reject('Rejected!'));
  8. //emit single value after 1 second
  9. const source = timer(1000);
  10. //catch rejected promise, returning observable containing error message
  11. const example = source.pipe(
  12. mergeMap(_ =>
  13. fromPromise(myBadPromise()).pipe(
  14. catchError(error => of(`Bad Promise: ${error}`))
  15. )
  16. )
  17. );
  18. //output: 'Bad Promise: Rejected'
  19. 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