Created
April 13, 2022 15:55
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
}) | |
); | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
When
retryWhen
just doesn't cut the mustard...