Skip to content

Instantly share code, notes, and snippets.

@UserGalileo
Created November 14, 2021 19:32
Show Gist options
  • Save UserGalileo/5e8f369706403def32474b60817b4511 to your computer and use it in GitHub Desktop.
Save UserGalileo/5e8f369706403def32474b60817b4511 to your computer and use it in GitHub Desktop.
Retry Interceptor
import {HttpContextToken, HttpEvent, HttpHandler, HttpInterceptor, HttpRequest} from '@angular/common/http';
import {Observable} from 'rxjs';
import {retry, tap} from 'rxjs/operators';
export const RETRY_COUNT = new HttpContextToken(() => 3);
export const ERROR_COUNT = new HttpContextToken(() => 0);
export class RetryInterceptor implements HttpInterceptor {
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
const retryCount = req.context.get(RETRY_COUNT);
return next.handle(req).pipe(
tap({
error: () => {
req.context.set(ERROR_COUNT, req.context.get(ERROR_COUNT) + 1);
},
}),
retry(retryCount)
);
}
}
/**
* Usage:
*
this.httpClient.get('...', {
context: new HttpContext().set(RETRY_COUNT, 5),
}).subscribe(() => {});
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment