File
Methods
intercept
|
intercept(req: HttpRequest, next: HttpHandler)
|
|
Parameters :
Name |
Type |
Optional |
req |
HttpRequest<any>
|
No
|
next |
HttpHandler
|
No
|
Returns : Observable<HttpEvent<any>>
|
Private
_onlineChanges$
|
Type : Observable<any>
|
|
Private
genericRetryStrategy
|
Default value : () => {...}
|
|
import {Inject, Injectable, PLATFORM_ID} from '@angular/core';
import {HttpEvent, HttpInterceptor, HttpHandler, HttpRequest, HttpErrorResponse} from '@angular/common/http';
import {fromEvent, Observable, throwError, timer} from 'rxjs';
import {isPlatformBrowser} from '@angular/common';
import {SnackBarService} from '../../snackbar/snack-bar.service';
import {retryWhen, catchError, mapTo, mergeMap} from 'rxjs/operators';
declare var window: any;
@Injectable()
export class HandlerErrorInterceptor implements HttpInterceptor {
private _onlineChanges$: Observable<any>;
constructor(
@Inject(PLATFORM_ID) private _platform: Object,
private _snackBar: SnackBarService
) {
}
private genericRetryStrategy = (
{
maxRetryAttempts = 3,
scalingDuration = 1000,
excludedStatusCodes = []
}: {
maxRetryAttempts?: number,
scalingDuration?: number,
excludedStatusCodes?: number[]
} = {}) => (attempts: Observable<any>) => {
return attempts.pipe(
mergeMap((error, i) => {
const retryAttempt = i + 1;
// if maximum number of retries have been met
// or response is a status code we don't wish to retry, throw error
if (
retryAttempt > maxRetryAttempts ||
excludedStatusCodes.find(e => e === error.status)
) {
return throwError(error);
}
console.log(
`Attempt ${retryAttempt}: retrying in ${retryAttempt *
scalingDuration}ms`
);
if (navigator.onLine) {
// retry after 1s, 2s, etc...
return timer(retryAttempt * scalingDuration);
} else {
return this._onlineChanges$;
}
})
);
}
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
if (isPlatformBrowser(this._platform)) {
this._onlineChanges$ = fromEvent(window, 'online').pipe(mapTo(true));
return next.handle(req)
.pipe(
retryWhen(this.genericRetryStrategy({
scalingDuration: 1000,
maxRetryAttempts: 5
})),
catchError((error: HttpErrorResponse) => {
let errorMessage;
if (error instanceof ErrorEvent) {
errorMessage = `Error client side: ${error.error.message}`;
} else {
errorMessage = `Error server side: STATUS: ${error.status} MESSAGE: ${error.message}`;
}
this._snackBar.setMessage('Ha ocurrido un error', 'OK', 3000);
return throwError(errorMessage);
})
);
} else {
return next.handle(req);
}
}
}