Angular - 在所有 HTTP 重试失败后捕获错误 [英] Angular - Catching error after all HTTP retry failed
本文介绍了Angular - 在所有 HTTP 重试失败后捕获错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用 Angular 服务从我的 API
获取数据.我实现了重试功能,以防获取数据失败.现在我需要在所有重试都耗尽时处理错误,但我无法捕捉到它.
I am using Angular Service to get data from my API
. I implemented retry feature in case of fetching data fails. Now i need to handle the error when all the retries wear out, but im not able to catch it.
以下是我的代码,
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.');
};
我可以成功重试 10 次,延迟 1 秒,但是当 10 次重试完成后,我想无法捕捉到错误.
I am succesfully able to retry 10 times with 1 sec delay, but when 10 retries complete, i want unable to catch the error.
注意:
我是 Angular 的新手,所以如果你能在这次电话会议中提出改进建议,欢迎你这样做.
I am new to Angular, so if you could suggest improvement in this call you're welcomed to do so.
推荐答案
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 资源
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!'))
);
};
这篇关于Angular - 在所有 HTTP 重试失败后捕获错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文