Skip to content

Instantly share code, notes, and snippets.

@alastair-todd
Created April 13, 2022 15:55
Show Gist options
  • Save alastair-todd/d7ff2fb1328aac32920cd23d05524325 to your computer and use it in GitHub Desktop.
Save alastair-todd/d7ff2fb1328aac32920cd23d05524325 to your computer and use it in GitHub Desktop.
Angular interceptor to retry the request given a specific error and also modify the request headers
import { Injectable } from '@angular/core';
import { HttpErrorResponse, HttpEvent, HttpHandler, HttpInterceptor, HttpRequest } from '@angular/common/http';
import { Observable, of, throwError } from 'rxjs';
import { delay, catchError, switchMap } from 'rxjs/operators';
import { LoggingService } from '@logging/logging.service';
@Injectable()
export class ObjectContextExceptionRetryInterceptor implements HttpInterceptor {
private retryCount = 3;
private retryWaitTime = 1500;
constructor(private logger: LoggingService) {}
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return this.makeRequest(req, next);
}
private makeRequest = (req: HttpRequest<any>, next: HttpHandler, retries = 0): Observable<HttpEvent<any>> => {
req = req.clone({
setHeaders: {
'x-attempt': (retries + 1).toString()
}
});
return next.handle(req).pipe(
catchError((errorResponse: HttpErrorResponse) => {
if (errorResponse.error.detail.startsWith('System.ObjectDisposedException') && retries <= this.retryCount) {
retries++;
this.logger.warn(`Remote object context disposed error. Retry: ${retries} of ${this.retryCount}`);
return of(errorResponse).pipe(delay(this.retryWaitTime), switchMap(() => this.makeRequest(req, next, retries)));
}
return throwError(errorResponse);
})
);
};
}
@alastair-todd
Copy link
Author

When retryWhen just doesn't cut the mustard...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment