为什么没有将此throwError捕获在catchError中?

时间:2019-09-24 00:33:18

标签: angular error-handling rxjs rxjs-pipeable-operators

我试图创建一个可管道的运算符,并在不满足特定条件的情况下抛出该异常。但是,我无法抛出并捕获该错误。

这是我的管道:

// My custom pipeable
export function waitFor<T>(thisToComplete$: Observable<any>) {
  return (beforeRunningThis$: Observable<T>) => {
    return new Observable<T>(observer =>
      thisToComplete$.pipe(first()).subscribe(x => {
        if (x !== 'Success') {
          console.log('Non success result encountered');
          return throwError('Rando IO Error');
        }
        return beforeRunningThis$.subscribe(observer);
      })
    );
  }
}

使用代码:

const preReq$ = timer(1000);
const dataReq$ = getData();

try {
  dataReq$
    .pipe(waitFor(preReq$), catchError(x => {
      console.log('Code here reached');
      return of('Error was handled either here')
    }))
    .subscribe(x => console.log(`I have result ${x.toString()}`));
} catch (e) {
  console.log('Error was handled here');
}

但是上述控制台均未记录。

这里是stackblitz

2 个答案:

答案 0 :(得分:1)

由于您使用的是Observable构造 observer.error是你扔的方式

    if (x !== 'Success') {
      console.log('Non success result encountered');
      observer.error('Rando IO Error');
    }

答案 1 :(得分:1)

您需要摆脱管道运算符中的错误处理。基本上,您在这里遇到错误:

dataReq$
    .pipe(waitFor(preReq$))
    .subscribe(x => { 
      console.log(`I have result ${x.toString()}`);
    }, error => {
       console.log('Code here reached');
       // handle error
    });