UNPKG

2.13 kBPlain TextView Raw
1
2import { Observable, ObservableInput } from 'rxjs';
3import { catchError as higherOrder } from 'rxjs/operators';
4
5/**
6 * Catches errors on the observable to be handled by returning a new observable or throwing an error.
7 *
8 * <img src="./img/catch.png" width="100%">
9 *
10 * @example <caption>Continues with a different Observable when there's an error</caption>
11 *
12 * Observable.of(1, 2, 3, 4, 5)
13 * .map(n => {
14 * if (n == 4) {
15 * throw 'four!';
16 * }
17 * return n;
18 * })
19 * .catch(err => Observable.of('I', 'II', 'III', 'IV', 'V'))
20 * .subscribe(x => console.log(x));
21 * // 1, 2, 3, I, II, III, IV, V
22 *
23 * @example <caption>Retries the caught source Observable again in case of error, similar to retry() operator</caption>
24 *
25 * Observable.of(1, 2, 3, 4, 5)
26 * .map(n => {
27 * if (n === 4) {
28 * throw 'four!';
29 * }
30 * return n;
31 * })
32 * .catch((err, caught) => caught)
33 * .take(30)
34 * .subscribe(x => console.log(x));
35 * // 1, 2, 3, 1, 2, 3, ...
36 *
37 * @example <caption>Throws a new error when the source Observable throws an error</caption>
38 *
39 * Observable.of(1, 2, 3, 4, 5)
40 * .map(n => {
41 * if (n == 4) {
42 * throw 'four!';
43 * }
44 * return n;
45 * })
46 * .catch(err => {
47 * throw 'error in source. Details: ' + err;
48 * })
49 * .subscribe(
50 * x => console.log(x),
51 * err => console.log(err)
52 * );
53 * // 1, 2, 3, error in source. Details: four!
54 *
55 * @param {function} selector a function that takes as arguments `err`, which is the error, and `caught`, which
56 * is the source observable, in case you'd like to "retry" that observable by returning it again. Whatever observable
57 * is returned by the `selector` will be used to continue the observable chain.
58 * @return {Observable} An observable that originates from either the source or the observable returned by the
59 * catch `selector` function.
60 * @method catch
61 * @name catch
62 * @owner Observable
63 */
64export function _catch<T, R>(this: Observable<T>, selector: (err: any, caught: Observable<T>) => ObservableInput<R>): Observable<T | R> {
65 return higherOrder(selector)(this);
66}