import { HttpErrorResponse, HttpEvent, HttpHandler, HttpInterceptor, HttpRequest, HttpStatusCode } from '@angular/common/http'; import { Inject, Injectable, Optional } from '@angular/core'; import { MonoTypeOperatorFunction, Observable, retry, throwError, timer } from 'rxjs'; import { catchError, tap } from 'rxjs/operators'; import { MAX_RETRIES_ON_SERVER_ERROR } from './max-retries.token'; import { ErrorService } from './error.service'; import { KeycloakService } from 'keycloak-angular'; function updateSeconds(seconds: number) { if (seconds === 0 || seconds === 1) { return seconds + 1; } else { return seconds * seconds; } } function backoffOnServerError(maxRetries = 3): MonoTypeOperatorFunction> { let seconds = 0; function delay(error: HttpErrorResponse) { seconds = updateSeconds(seconds); if (error.status < HttpStatusCode.InternalServerError && error.status !== 0) { return throwError(() => error); } console.error('An error occurred: ', error); console.error(`Retrying in ${seconds} seconds...`); return timer(seconds * 1000); } return retry({ count: maxRetries, delay }); } @Injectable() export class ServerErrorInterceptor implements HttpInterceptor { private readonly _urlsWithError = new Set(); constructor( private readonly _errorService: ErrorService, private readonly _keycloakService: KeycloakService, @Optional() @Inject(MAX_RETRIES_ON_SERVER_ERROR) private readonly _maxRetries: number, ) {} intercept(req: HttpRequest, next: HttpHandler): Observable> { return next.handle(req).pipe( catchError((error: HttpErrorResponse) => { // token expired if (error.status === HttpStatusCode.Unauthorized) { this._keycloakService.logout(); } // server error if (error.status >= HttpStatusCode.InternalServerError) { this._errorService.set(error); this._urlsWithError.add(req.url); } return throwError(() => error); }), backoffOnServerError(this._maxRetries || 3), tap(() => { if (this._urlsWithError.has(req.url)) { this._errorService.setOnline(); this._urlsWithError.delete(req.url); } }), ); } }