catchError

签名: catchError(project : function): Observable

优雅地处理 observable 序列中的错误


:warning: 记住要在 catch 函数中返回一个 observable !


catchError - 图2

示例

( 示例测试 )

示例 1: 捕获 observable 中的错误

( jsBin |
jsFiddle )

  1. import { _throw } from 'rxjs/observable/throw';
  2. import { catchError } from 'rxjs/operators';
  3. // 发出错误
  4. const source = _throw('This is an error!');
  5. // 优雅地处理错误,并返回带有错误信息的 observable
  6. const example = source.pipe(catchError(val => of(`I caught: ${val}`)));
  7. // 输出: 'I caught: This is an error'
  8. const subscribe = example.subscribe(val => console.log(val));
示例 2: 捕获拒绝的 promise

( jsBin |
jsFiddle )

  1. import { timer } from 'rxjs/observable/timer';
  2. import { fromPromise } from 'rxjs/observable/timer';
  3. import { of } from 'rxjs/observable/timer';
  4. import { mergeMap, catchError } from 'rxjs/operators';
  5. // 创建立即拒绝的 Promise
  6. const myBadPromise = () =>
  7. new Promise((resolve, reject) => reject('Rejected!'));
  8. // 1秒后发出单个值
  9. const source = timer(1000);
  10. // 捕获拒绝的 promise,并返回包含错误信息的 observable
  11. const example = source.pipe(
  12. mergeMap(_ =>
  13. fromPromise(myBadPromise()).pipe(
  14. catchError(error => of(`Bad Promise: ${error}`))
  15. )
  16. )
  17. );
  18. // 输出: 'Bad Promise: Rejected'
  19. const subscribe = example.subscribe(val => console.log(val));

其他资源


:file_folder: 源码: https://github.com/ReactiveX/rxjs/blob/master/src/internal/operators/catch.ts