【发布时间】: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