Skip to content

Latest commit

 

History

History
62 lines (45 loc) · 1.86 KB

catch.md

File metadata and controls

62 lines (45 loc) · 1.86 KB

catch

signature: catch(project : function): Observable

Gracefully handle errors in an observable sequence.


⚠️ Remember to return an observable from the catch function!


Examples

( example tests )

Example 1: Catching error from observable

( jsBin | jsFiddle )

//emit error
const source = Rx.Observable.throw('This is an error!');
//gracefully handle error, returning observable with error message
const example = source.catch(val => Rx.Observable.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 )

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

Additional Resources


📁 Source Code: https://github.com/ReactiveX/rxjs/blob/master/src/operator/catch.ts