codecamp

RxJS catchError

通过返回新的可观察对象或引发错误,在可观察对象上捕获错误。

catchError<T, O extends ObservableInput<any>>(selector: (err: any, caught: Observable<T>) => O): OperatorFunction<T, T | ObservedValueOf<O>>

参量

选择器 一个以参数为参数的函数 err,这是错误,而 caught,其中 是可观察的源,以防您想通过再次返回来“重试”该可观察的源。 无论观察到什么 将返回, selector将用于继续可观察的链。

returns

OperatorFunction<T, T | ObservedValueOf<O>>:可观察到的事物,其来源或来源是 捕获 selector功能。

描述

catch marble diagram

例子

发生错误时继续使用其他 Observable

import { of } from 'rxjs';
import { map, catchError } from 'rxjs/operators';


of(1, 2, 3, 4, 5).pipe(
    map(n => {
       if (n === 4) {
           throw 'four!';
      }
     return n;
    }),
    catchError(err => of('I', 'II', 'III', 'IV', 'V')),
  )
  .subscribe(x => console.log(x));
  // 1, 2, 3, I, II, III, IV, V

重传捕获的源,如果出现错误,则再次可观察,类似于 retry()运算符

import { of } from 'rxjs';
import { map, catchError, take } from 'rxjs/operators';


of(1, 2, 3, 4, 5).pipe(
    map(n => {
       if (n === 4) {
         throw 'four!';
      }
         return n;
    }),
    catchError((err, caught) => caught),
    take(30),
  )
  .subscribe(x => console.log(x));
  // 1, 2, 3, 1, 2, 3, ...

当源 Observable 引发错误时引发新错误

import { of } from 'rxjs';
import { map, catchError } from 'rxjs/operators';


of(1, 2, 3, 4, 5).pipe(
    map(n => {
      if (n === 4) {
        throw 'four!';
      }
      return n;
    }),
    catchError(err => {
      throw 'error in source. Details: ' + err;
    }),
  )
  .subscribe(
    x => console.log(x),
    err => console.log(err)
  );
  // 1, 2, 3, error in source. Details: four!
RxJS bufferWhen
RxJS CombineAll
温馨提示
下载编程狮App,免费阅读超1000+编程语言教程
取消
确定
目录

RxJS operators

RxJS fetch

RxJS testing

关闭

MIP.setData({ 'pageTheme' : getCookie('pageTheme') || {'day':true, 'night':false}, 'pageFontSize' : getCookie('pageFontSize') || 20 }); MIP.watch('pageTheme', function(newValue){ setCookie('pageTheme', JSON.stringify(newValue)) }); MIP.watch('pageFontSize', function(newValue){ setCookie('pageFontSize', newValue) }); function setCookie(name, value){ var days = 1; var exp = new Date(); exp.setTime(exp.getTime() + days*24*60*60*1000); document.cookie = name + '=' + value + ';expires=' + exp.toUTCString(); } function getCookie(name){ var reg = new RegExp('(^| )' + name + '=([^;]*)(;|$)'); return document.cookie.match(reg) ? JSON.parse(document.cookie.match(reg)[2]) : null; }