- catchError
- 签名:
catchError(project : function): Observable
- 签名:
- 优雅地处理 observable 序列中的错误
- 示例
- 示例 1: 捕获 observable 中的错误
- 示例 2: 捕获拒绝的 promise
- 示例
- 其他资源
catchError
签名: catchError(project : function): Observable
优雅地处理 observable 序列中的错误
记住要在 catch 函数中返回一个 observable !
示例
( 示例测试 )
示例 1: 捕获 observable 中的错误
( jsBin |
jsFiddle )
import { _throw } from 'rxjs/observable/throw';
import { catchError } from 'rxjs/operators';
// 发出错误
const source = _throw('This is an error!');
// 优雅地处理错误,并返回带有错误信息的 observable
const example = source.pipe(catchError(val => of(`I caught: ${val}`)));
// 输出: 'I caught: This is an error'
const subscribe = example.subscribe(val => console.log(val));
示例 2: 捕获拒绝的 promise
( jsBin |
jsFiddle )
import { timer } from 'rxjs/observable/timer';
import { fromPromise } from 'rxjs/observable/timer';
import { of } from 'rxjs/observable/timer';
import { mergeMap, catchError } from 'rxjs/operators';
// 创建立即拒绝的 Promise
const myBadPromise = () =>
new Promise((resolve, reject) => reject('Rejected!'));
// 1秒后发出单个值
const source = timer(1000);
// 捕获拒绝的 promise,并返回包含错误信息的 observable
const example = source.pipe(
mergeMap(_ =>
fromPromise(myBadPromise()).pipe(
catchError(error => of(`Bad Promise: ${error}`))
)
)
);
// 输出: 'Bad Promise: Rejected'
const subscribe = example.subscribe(val => console.log(val));
其他资源
- 错误处理操作符: catch - André Staltz
源码: https://github.com/ReactiveX/rxjs/blob/master/src/internal/operators/catch.ts