[英]rxjs error handling with catchError and retry
我正在嘗試使用 catchError 運算符捕獲 rxjs 中的錯誤,並且僅當我收到errno=215
時才想重試 3 次
return this.httpService.post(url, data).pipe(
tap(() => {
console.log(`some debugging info`);
}),
map((response) => responseAdaptor(response)),
retryWhen((error) => {
return error.pipe(
scan((acc, error) => {
// RETRY ONLY IF ERROR error.errno == 215
if (acc > 2) throw error;
return acc + 1;
}, 0),
delay(1000)
);
}),
catchError((error) => {
console.log(error);
// Here I want the use `throwError`
return of({ error: error.response });
})
);
這是我嘗試過的但不幸的是不知道如何結合掃描計數器和 errno。
您可以通過將catchError
運算符移動到retryWhen
之前,並使用take(3)
運算符將重試嘗試限制為 3 次而不是使用scan
一次來實現。
您可以嘗試以下操作:
this.httpService.post(url, data).pipe(
tap(() => {
console.log(`some debugging info`);
}),
map((response) => responseAdaptor(response)),
catchError((error) => {
// If the error is 215 then throw the error to trigger the retryWhen,
// Otherwise return the error response.
if (error.errno === 215) {
return throwError(() => error);
}
return of({ error: error.response });
}),
retryWhen((errors) => errors.pipe(delay(1000), take(3)))
);
這將在 3 次重試嘗試后完成主Observable
。 如果你想包裝錯誤並在 3 次嘗試后保持主Observable
工作,則retryWhen
回調返回的 observable 應該返回以下內容:
// This should be added directly after `take(3)` operator on the `errors` pipe.
concatMap((error) => of({ error: error.response })
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.