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

标签 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

最佳答案

由于您正在使用Observable构造observer.error是你怎么扔的

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

关于angular - 为什么没有将此throwError捕获在catchError中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58071648/

相关文章:

html - 在内容加载之前隐藏 css 中的底部边框

json - 将 json 数据更改为 Angular 2 中的 Typescript 接口(interface)对象

python - 想输入诸如 “01”和 “07”之类的整数,但出现 “invalid literal”错误。总体方案是RLE压缩机

scala - 为什么 `scala.util.Try(date)` 未定义时 `Failure` 不返回 `date`?

javascript - 使用 redux observable 取消请求不起作用

angular - 存储 Observable 的解析值,以便在模板中多次使用

javascript - 如何将订阅放入 RxJS 或 Angular2 中 Observables 的过滤器中?

javascript - 如何在 Angular 7 中使用窗口对象

java - 在Java中检查输入是5、10、15、20、25还是30

javascript - Angular 8 在异步调用链之后返回可观察的