Angular10教程–4.5 RxJs-错误处理类操作符

Angular10教程--4.5 RxJs-错误处理类操作符

这一节介绍RxJs

错误是开发中不幸的副作用。这些提供了一些高效的方式来优雅地处理错误并且在它们应该发生的情况下重试逻辑。

之前演示过,如果 Observable 内部发出错误,只会进入 error回调。

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

of(1, 2, 3, 4, 5).pipe(
  map(n => {
    if (n === 4) {
      throw new Error('four err!');
    }
    return n;
  })
).subscribe(
  x => console.log(x), // 输出:1 2 3
  error => console.error('err', error),
  () => console.log('complete')
);
可以通过一些改变这行为:

catchError

无视错误,返回一个新的 Observable

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

of(1, 2, 3, 4, 5).pipe(
  map(n => {
    if (n === 4) {
      throw new Error('four err!');
    }
    return n;
  }),
  catchError(err => of('I', 'II', 'III', 'IV', 'V')),
).subscribe(
  x => console.log(x), // 输出:1 2 3 I II III IV V
  error => console.error('err', error), // 不会走这里
  () => console.log('complete')
);

重试错误

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

of(1, 2, 3, 4, 5).pipe(
  map(n => {
    if (n === 4) {
      throw new Error('four err!');
    }
    return n;
  }),
  catchError((err, caught) => caught),
  take(10),
).subscribe(x => console.log(x)); // 输出1 2 3,然后重试,一直输出10数值

也可以抛出一个新的错误

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

of(1, 2, 3, 4, 5).pipe(
  map(n => {
    if (n === 4) {
      throw new Error('four err!');
    }
    return n;
  }),
  catchError(err => {
    throw new Error('error in source. Details: ' + err);
  }),
)
  .subscribe(
    x => console.log(x),
    err => console.error('err ', err),
    () => console.log('complete') // 不会走这里
  );

retry

发生错误后重试指定次数

import { interval, of } from 'rxjs';
import { mergeMap, retry } from 'rxjs/operators';

const source = interval(1000);
const example = source.pipe(
  mergeMap(val => {
    if (val > 2){
      return throwError('Error!');
    }
    return of(val);
  }),
  // 重试两次
  retry(2)
);
// 输出两次0 1 2 然后走error回调
const subscribe = example.subscribe({
  next: val => console.log(val),
  error: val => console.error('err ', `${val}: Retried 2 times then quit!`)
});

retryWhen

发生错误后 自定义重试策略,参数是个回调函数,返回 Observable

import { interval, of } from 'rxjs';
import { delay, tap, retryWhen } from 'rxjs/operators';

const source = interval(1000);
const example = source.pipe(
  map(val => {
    if (val > 2) {
      // 错误将由 retryWhen 接收
      throw val;
    }
    return val;
  }),
  retryWhen(errors =>
    errors.pipe(
      // 输出错误信息
      tap(val => console.log(`Value ${val} 太大了!`)),
      // 3秒后重试
      delay(3000)
    )
  )
);
const subscribe = example.subscribe(
  val => console.log(val),
  error => console.error('err ', error)
);

前面逍遥乐也分享过一篇文章《史上最全Rxjs从入门到精通的学习知识点整理》,看完这个,你就能熟悉各种rxjs的基本操作了。