我不确定在使用 fork时如何获取特定API调用的异常消息
我有如下编写的代码
reqs = [];
if (shouldUpdatePhone) {
reqs.push(this.customerService.updatePhone(phoneUpdateRequest))
}
if (shouldUpdateAddress) {
reqs.push(this.customerService.updateAddress(addressUpdateRequest))
}
forkJoin(reqs).subscribe(result => {
console.log('result :', result);
}, error => {
//How to get error message for particular api call?
});
如果一个或两个api由于某种原因失败。我应该如何确定哪个api引发异常。
最佳答案
您不能这样做,因为forkJoin
会在任何可观察对象遇到的第一个错误上引发错误。如果发出的错误中没有任何东西告诉您它是来自什么,例如检查错误代码,则可以选择从服务调用中创建可观察对象时处理错误。
reqs = [];
if (shouldUpdatePhone) {
reqs.push(
this.customerService.updatePhone(phoneUpdateRequest).pipe(catchError(() => {
throw 'phoneUpdateError';
});
)
}
if (shouldUpdateAddress) {
reqs.push(
this.customerService.updateAddress(phoneUpdateRequest).pipe(catchError(() => {
throw 'addressUpdateError';
});
)
}
现在,您可以检查抛出了哪个错误。但是,您不必通过错误处理来执行此操作;您还可以将错误映射到成功的响应并进行处理。
最终,我建议结合使用这些API调用。
关于Angular 6 : Error handling with forkJoin,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/51993575/