angular - 如何在 rxjs 中使用 retryWhen 正确处理错误
问题描述
当出现 502 bad gateway 错误时,我需要重试特定的 API 调用大约 3 次。重试可能会稍微增加延迟。这是组件中的代码。
一些.component.ts
someMethod() {
let attempt = 0;
this.someService.AppendSubject(this.subject)
.pipe(retryWhen(errors => errors.pipe(
tap(error => this.retryApi(error, ++attempt, 'Server busy. Retrying request', this.subject))
)))
.subscribe(response => {
//do something with response
});
}
retryApi(error: any, attempt: number, retryMessage: string, data?: any) {
delay(this.duration*attempt)
//show toast with retryMessage
if (attempt > this.retryLimit) {
//show some message
if (data)
this.notifyFailure(data);
throw error;
}
}
notifyFailure(data: any) {
this.someService.notifyFailure(data);
}
一些.service.ts
public AppendSubject(data: any) {
return this.http.post<any>(`{env.api}/appendsubject/`, data);
}
public notifyFailure(data: any) {
return this.http.post<any>(`{env.api}/notifyfailure/`, data);
}
- 在服务器端根本没有命中 notifyFailure 端点。
这是由于我在重试中如何做/不做错误捕获吗?如何正确捕获上述代码中的错误并且不阻碍或终止进一步的 notifyFailure 调用?
注意:我目前没有在拦截器中执行此操作,因为此时这仅适用于特定 API。我在组件中编写重试处理程序,而不是在some.service.ts
级别,因为我不知道如何做到这一点,同时在组件中显示适当的 toast 和弹出窗口。
解决方案
再会!我更喜欢使用这种方法:
您的服务:
getSomething(retryCount: number = 0, retryInterval: number = 1000) {
return this.http.get(this.getSomethingUrl).pipe(
retryWhen((error: Observable<any>) => error.pipe(
delay(retryInterval),
take(retryCount)
))
);
}
在组件中:
this.service.getSomething(3, 2000).subscribe(response => {
// Handle success
}, error => {
// Here you can send a request to your BE (triggers only after 3 failed requests in this case), to notify about the occurred error
// Also you can do it in your pipe using `catchError` rxjs operator
});
推荐阅读
- python - 从 S3 读取 KMS 加密文件
- regex - 如何重写文件并在上面移动非匹配行。正则表达式
- opencv - 如何在共享(非专用)GPU 内存中分配 GpuMat?
- c# - 来自 C# 的 SQL 无服务器命令
- python - 加快图中的采样速度
- javascript - 错误:连接丢失:服务器关闭了连接。在 Protocol.end
- javascript - 尝试循环通过 API GET 请求向量
- algorithm - 以下排序算法对哪种输入数据好/坏?
- git - Git 命令查找特定类型的上一个分支
- javascript - 这是来自 Pro React 16 book kosher 的 Redux reducer 示例吗?