当前位置: 首页 > 文档资料 > 学习 RxJS 操作符 >

catchError

优质
小牛编辑
139浏览
2023-12-01

catch / catchError

函数签名: catchError(project : function): Observable

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


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


示例

( 示例测试 )

示例 1: 捕获 observable 中的错误

( StackBlitz | jsBin | jsFiddle )

// RxJS v6+
import { throwError, of } from 'rxjs';
import { catchError } from 'rxjs/operators';
// 发出错误
const source = throwError('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

( StackBlitz | jsBin | jsFiddle )

// RxJS v6+
import { timer, from, of } from 'rxjs';
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(_ =>
    from(myBadPromise()).pipe(catchError(error => of(`Bad Promise: ${error}`)))
  )
);
// 输出: 'Bad Promise: Rejected'
const subscribe = example.subscribe(val => console.log(val));

其他资源


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