RxJs 像重试一样使用 catchError
RxJs use catchError like retry
我正在寻找为 http 调用重复/递归调用 catchError 的可能性。起初我只是使用 retry(x)
但现在我需要修改请求以防出错。
现在 catchError
只调用一次(当然)。如何修改?
export class HttpErrorInterceptor implements HttpInterceptor {
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
let attempts = 0;
return next.handle(request).pipe(
catchError(e => {
attempts++;
if (attempts < 5) { return next.handle(request.clone({ ...{} })); }
throw e;
})
);
}
}
因此,如果您只需要第一次修改,只需将重试放在 catchError
:
内的修改后的可观察对象上
export class HttpErrorInterceptor implements HttpInterceptor {
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return next.handle(request).pipe(
catchError(e => {
return next.handle(request.clone({ ...{} })).pipe(retry(4));
})
);
}
}
如果你每次都需要修改,递归错误处理程序会做:
export class HttpErrorInterceptor implements HttpInterceptor {
private handleError(request: HttpRequest<any>, next: HttpHandler, error, attempts: number) {
return next.handle(request.clone({ ...{} })).pipe(
catchError(e => (attempts < 5) ? this.handleError(request, next, e, attempts + 1) : throwError(e))
)
}
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return next.handle(request).pipe(
catchError(e => this.handleError(request, next, e, request, 1))
);
}
}
我正在寻找为 http 调用重复/递归调用 catchError 的可能性。起初我只是使用 retry(x)
但现在我需要修改请求以防出错。
现在 catchError
只调用一次(当然)。如何修改?
export class HttpErrorInterceptor implements HttpInterceptor {
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
let attempts = 0;
return next.handle(request).pipe(
catchError(e => {
attempts++;
if (attempts < 5) { return next.handle(request.clone({ ...{} })); }
throw e;
})
);
}
}
因此,如果您只需要第一次修改,只需将重试放在 catchError
:
export class HttpErrorInterceptor implements HttpInterceptor {
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return next.handle(request).pipe(
catchError(e => {
return next.handle(request.clone({ ...{} })).pipe(retry(4));
})
);
}
}
如果你每次都需要修改,递归错误处理程序会做:
export class HttpErrorInterceptor implements HttpInterceptor {
private handleError(request: HttpRequest<any>, next: HttpHandler, error, attempts: number) {
return next.handle(request.clone({ ...{} })).pipe(
catchError(e => (attempts < 5) ? this.handleError(request, next, e, attempts + 1) : throwError(e))
)
}
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return next.handle(request).pipe(
catchError(e => this.handleError(request, next, e, request, 1))
);
}
}