Skip to content

Instantly share code, notes, and snippets.

@ninadvadujkar
Last active April 3, 2023 08:54
Show Gist options
  • Save ninadvadujkar/bb1f2804f9a73b02234bb3813304805f to your computer and use it in GitHub Desktop.
Save ninadvadujkar/bb1f2804f9a73b02234bb3813304805f to your computer and use it in GitHub Desktop.
A basic Angular HTTP Interceptor to retry requests when there's an error
import { Injectable } from '@angular/core';
import { HttpEvent, HttpHandler, HttpInterceptor, HttpRequest, HttpResponse } from '@angular/common/http';
import { Observable, timer, throwError, of } from 'rxjs';
import { retryWhen, tap, mergeMap } from 'rxjs/operators';
@Injectable()
export class HttpRequestInterceptor implements HttpInterceptor {
retryDelay = 2000;
retryMaxAttempts = 2;
constructor() { }
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return next.handle(request)
.pipe(
this.retryAfterDelay(),
);
}
retryAfterDelay(): any {
return retryWhen(errors => {
return errors.pipe(
mergeMap((err, count) => {
// throw error when we've retried ${retryMaxAttempts} number of times and still get an error
if (count === this.retryMaxAttempts) {
return throwError(err);
}
return of(err).pipe(
tap(error => console.log(`Retrying ${error.url}. Retry count ${count + 1}`)),
mergeMap(() => timer(this.retryDelay))
);
})
);
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment