[英]RxJs retryWhen throwing exception before all retry attempt
我正在嘗試實現一個 api 調用
我試圖實現這里提到的 - Rxjs Retry with Delay function
以下是我的代碼段
Api 來電
delay = 5000; retryCount = 5; return this.httpClient.post(http://localhost:8080/info,JSON.stringify(data)).pipe( retryWhen(errors => errors.pipe( delay(this.delay), take(this.retryCount), tap(val => { console.log('Retrying.'); }), concatMap(() => Observable.throw(new Error('Retry limit exceeded;'))) ) ) );
處理響應
this.searchService.searchInfo(param1, param2).subscribe(data => { this.handleSuccessResponse(data) }, (error) => { if (error) { // Handle specific error here handleErrorResponse(error); } }); handleSuccessResponse(data){ // handle success response here } handleErrorResponse(error){ // Handle generic error here }
我遇到的問題是,在我在代碼中提到的重試 5 次之前,concatMap 中的異常被拋出。 我在這里缺少什么?
我正在使用 RxJS 6.4 和 Angular12
我瀏覽了learnRxjs
文檔並得到了這個通用方法,這似乎滿足您的要求!
import { Observable } from 'rxjs/Observable';
import { _throw } from 'rxjs/observable/throw';
import { timer } from 'rxjs/observable/timer';
import { mergeMap, finalize } from 'rxjs/operators';
export const genericRetryStrategy =
({
maxRetryAttempts = 3,
scalingDuration = 1000,
excludedStatusCodes = [],
}: {
maxRetryAttempts?: number;
scalingDuration?: number;
excludedStatusCodes?: number[];
} = {}) =>
(attempts: Observable<any>) => {
return attempts.pipe(
mergeMap((error, i) => {
const retryAttempt = i + 1;
// if maximum number of retries have been met
// or response is a status code we don't wish to retry, throw error
if (
retryAttempt > maxRetryAttempts ||
excludedStatusCodes.find((e) => e === error.status)
) {
return _throw('Retry limit exceeded!');
}
console.log(
`Attempt ${retryAttempt}: retrying in ${
retryAttempt * scalingDuration
}ms`
);
// retry after 1s, 2s, etc...
return timer(retryAttempt * scalingDuration);
}),
finalize(() => console.log('We are done!'))
);
};
情況1
res === null
總是repeat
(延遲 500ms)retry
API 錯誤 5 次(延遲 500ms)api$.pipe(
repeat({ delay: 500 }),
skipWhile((res) => res === null),
take(1),
retry({ count: 5, delay: 500 })
).subscribe(observer);
案例2
res === null
+ API 錯誤= 5 次(延遲 500ms)api$.pipe(
skipWhile((res) => res === null),
throwIfEmpty(),
retry({ count: 5, delay: 500 })
).subscribe(observer);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.