使用 catchError 和重试的 rxjs 错误处理
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
回调的可观察 return 应该 return 以下内容:
// This should be added directly after `take(3)` operator on the `errors` pipe.
concatMap((error) => of({ error: error.response })
我正在尝试使用 catchError 运算符捕获 rxjs 中的错误,并且仅当我收到 errno=215
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
回调的可观察 return 应该 return 以下内容:
// This should be added directly after `take(3)` operator on the `errors` pipe.
concatMap((error) => of({ error: error.response })