catchError / throwError

·2023년 1월 15일
0

RxJS

목록 보기
8/9

catchError operator

오퍼레이터로서 가공과정에서 던져진 error를 처리하며 옵저버블을 반환하는 핸들러를 인자로 한다.

getConfig() {
  return this.http.get<Config>(this.configUrl)
    .pipe(
      catchError(this.handleError)
    );
}

http.get은 Config타입의 옵저버블객체를 반환하고 httpClient가 throw 에러를 한다면 catchError오퍼레이터에 포착되고 handleError가 에러를 처리한다.

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

catchError의 에러핸들러에서 다른 옵저버블객체를 반환할 수 도 있다.

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

에러핸들러는 err은 any타입 에러객체이고 caught는 원 옵저버블소스 인자를 사용하고 옵저버블을 반환해야 한다.


    scheduled([1,2,3,4,5], asyncScheduler).pipe(
      map(val=>{
        if(val==4){
          throw 'error';
        }
        return val;
      })
    ).subscribe({
      next:val=>console.log(val),
      error:()=>console.log('ERROR'),
    });

구독핸들러에서 발생된 에러를 처리할 수 있기때문에 catchError오퍼레이터가 꼭 필요한 것은 아니다.

그러나 catchError를 사용하면 구독전에 발생에러에대해 적절하게 대응할 수 있다.

    scheduled([1,2,3,4,5], asyncScheduler).pipe(
      map(val=>{
        if(val==4){
          throw 'error';
        }
        return val;
      }),
      catchError(err=>scheduled([5],asyncScheduler))
    ).subscribe({
      next:val=>console.log(val),
      error:()=>console.log('ERROR'),
    });

가공과정중에 catchError가 적당한 옵저버블을 반환하기때문에 구독핸들러에서는 에러가 발생하지 않은것이 된다.



throwError function

throwError(errorOrErrorFactory: any, scheduler?: SchedulerLike): Observable<never>

never타입의 에러옵저버블객체를 반환한다.

    let errorCount = 0;

    const error$ = throwError(()=>{
      const error:any = new Error(`This is error number ${++errorCount}`);
      error.timestamp = Date.now();
      return error;
    });

    error$.subscribe({
      error:(err)=>{
        console.log('message : '+err.message);
        console.log('time : '+err.timestamp);
      }
    });

    error$.subscribe({
      error:(err)=>{
        console.log('message : '+err.message);
        console.log('time : '+err.timestamp);
      }
    })

throwError는 에러옵저버블을 반환하므로 구독핸들러에서 에러처리를 할 수 있다.



catchError와 throwError를 같이 사용해보자

    of(1, 2, 3, 4, 5)
    .pipe(
      map(n => {
        if (n === 4) {
          throw 'four!';
        }
        return n;
      }),
      catchError(err => throwError(()=>{
        console.log(err);
        return new Error('error!!!!!!!!!!!!!');
      }))
    )
    .subscribe({
      next:val=>console.log(val),
      error:err=>console.log('///////////'+err)
    });

n이 4일때 throw 'four!'로 에러를 던진다.

옵저버블 가공과중중에 에러가 발생했으므로 catchError오퍼레이터가 처리한다.

catchError는 옵저버블을 반환하는 핸들러인자를 가져야 한다.

에러유형을 구분해서 구체적인 에러정보를 가진 옵저버블을 반환하는 throwError함수를 사용한다.

구독핸들러의 error는 가공과중에 throw '에러';를 처리할수도 있지만 catchError가 새로운 정상적인 옵저버블을 반환하면 정상적인 데이터방출로 처리되어 next에서 처리될것이다.

catchError가 throwError로 에러옵저버블을 반환하면 error에서 처리한다.

0개의 댓글