catchError

lee jae hwan·2022년 10월 3일
0

RxJS

목록 보기
20/21

옵저버블에서 발생된 에러가 발생했을때 새로운 옵저버블을 반환하거나 에러를 던진다.

import { of, map, catchError } from 'rxjs';
 
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

map함수에서 옵저버블이 에러를 발생시키면 catchError가 에러를 감지하여 함수가 처리한다.

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

err은 any타입 에러객체이고 caught는 원 옵저버블소스이며 에러처리함수에서 에러를 처리하고 다시 옵저버블객체를 반환하면 다시 진행한다.

import { of, map, catchError, take } from 'rxjs';
 
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, ...

caught 원 옵저버블소스를 다시 방출하므로 4에서 에러가 발생하고 다시 방출하는 무한반복이 발생한다.

그래서 take를 사용한 것이다.

import { of, map, catchError } from 'rxjs';
 
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({
    next: x => console.log(x),
    error: err => console.log(err)
  });
  // 1, 2, 3, error in source. Details: four!

catchError에서 에러를 처리하고 다시 에러를 발생시키면 구독함수에서 error함수가 호출된다.

0개의 댓글