gpt4 book ai didi

Angular - 在所有 HTTP 重试失败后捕获错误

转载 作者:可可西里 更新时间:2023-11-01 16:49:22 28 4
gpt4 key购买 nike

我正在使用 Angular 服务从我的 API 获取数据。我在获取数据失败的情况下实现了重试功能。现在我需要在所有重试都用完时处理错误,但我无法捕获它。

以下是我的代码,

public getInfoAPI(category:string, id:string = "", page:string = "1", limit:string = "10"){
var callURL : string = '';

if(!!id.trim() && !isNaN(+id)) callURL = this.apiUrl+'/info/'+category+'/'+id;
else callURL = this.apiUrl+'/info/'+category;

return this.http.get(callURL,{
params: new HttpParams()
.set('page', page)
.set('limit', limit)
}).pipe(
retryWhen(errors => errors.pipe(delay(1000), take(10), catchError(this.handleError)))//This will retry 10 times at 1000ms interval if data is not found
);
}
// Handle API errors
handleError(error: HttpErrorResponse) {
console.log("Who's there?");
if (error.error instanceof ErrorEvent) {
// A client-side or network error occurred. Handle it accordingly.
console.error('An error occurred:', error.error.message);
} else {
// The backend returned an unsuccessful response code.
// The response body may contain clues as to what went wrong,
console.error(
`Backend returned code ${error.status}, ` +
`body was: ${error.error}`);
}
// return an observable with a user-facing error message
return throwError(
'Something bad happened; please try again later.');
};

我能够以 1 秒的延迟成功重试 10 次,但是当 10 次重试完成时,我想无法捕捉到错误。

enter image description here

注意:

我是 Angular 的新手,所以如果你能在这次通话中提出改进建议,我们欢迎你这样做。

最佳答案

    return this.http.get(callURL,{
params: new HttpParams()
.set('page', page)
.set('limit', limit)
}).pipe(
retryWhen(genericRetryStrategy({maxRetryAttempts: 10, scalingDuration: 1})),
catchError(this.handleError)
);

genericRetryStrategy 出自 retrywhen resource

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 throwError(error);
}
console.log(
`Attempt ${retryAttempt}: retrying in ${retryAttempt *
scalingDuration}ms`
);
// retry after 1s, 2s, etc...
return timer(retryAttempt * scalingDuration);
}),
finalize(() => console.log('We are done!'))
);
};

Stackblitz

关于Angular - 在所有 HTTP 重试失败后捕获错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58393499/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com