【问题标题】:RxJs throwError does not trigger catch in PromiseRxJs throwError 不会在 Promise 中触发 catch
【发布时间】:2020-02-27 23:49:08
【问题描述】:

我有一个转换为承诺的 Api 调用。我在可观察对象中的 handleError 函数通过 throwError 重新抛出。这个重新抛出的错误不会触发外部 Promise 链中的任何捕获。

callApi() {    
  return this.http.get(`${this.baseUrl}/someapi`)
    .pipe(
      map((data: any) => this.extractData(data)),
      catchError(error => this.handleError(error))
    ).toPromise();

handleError(error) {
  console.error(error);
  return throwError(error || 'Server error');
}

调用代码...

this.someService.callApi()
  .then((response) => {
    // THIS GETS CALLED AFTER throwError
    // do something cool with response
    this.someVar = response;
  })
  .catch((error) => {
    // WE NEVER GET TO HERE, even when I force my api to throw an error
    console.log(`Custom error message here. error = ${error.message}`);
    this.displayErrorGettingToken();
  });

为什么 throwError 不触发 Promise 捕获?

【问题讨论】:

  • 错误到底是在哪里触发的?如果是 HTTP 调用,那么你所拥有的应该可以工作。如果错误是从this.extractData() 中触发的,那么只要您使用throw new Error 表单而不是简单地返回throwError,您所拥有的应该仍然有效。如果您使用后者,请将map 换成switchMap。 (顺便说一句,混合 promise 和 observables 似乎很不寻常,所以我希望你知道你在做什么。)

标签: promise rxjs observable


【解决方案1】:

尽可能不要使用toPromise()。 使用 subscribe 而不是 then。 此外,当您在管道中捕获错误时,它不会被抛出,因为您已经捕获了它,而且当您在捕获错误中抛出错误时,它不会被发送到您响应的常规管道流中。


callApi() {    
  return this.http.get(`${this.baseUrl}/someapi`);
}

这完全没问题。 Http.get() 返回一个可观察的单例流,它只发出一个值然后完成。订阅Observable


this.someService.callApi()
  .subscribe((response) => {
    // THIS GETS CALLED always wenn everything is ok
    this.someVar = response;
  }, 
  (error:HttpErrorResponse) =>{
       console.log(`Custom error message here. error ${error.message}`);
    this.displayErrorGettingToken();
  }); 

Observable 就像是 promise 的扩展版本。用它。

【讨论】:

    猜你喜欢
    • 2019-01-12
    • 2019-10-08
    • 1970-01-01
    • 2022-01-13
    • 2023-03-12
    • 1970-01-01
    • 2022-07-11
    • 2017-06-08
    • 1970-01-01
    相关资源
    最近更新 更多