2021-03-17 14:39:33 +01:00
|
|
|
import {Injectable, isDevMode} from '@angular/core';
|
2021-03-15 12:54:46 +01:00
|
|
|
import {
|
|
|
|
HttpRequest,
|
|
|
|
HttpHandler,
|
|
|
|
HttpEvent,
|
|
|
|
HttpInterceptor, HttpErrorResponse
|
|
|
|
} from '@angular/common/http';
|
|
|
|
import {Observable, throwError} from 'rxjs';
|
2021-03-21 14:11:05 +01:00
|
|
|
import {catchError, retry} from 'rxjs/operators';
|
|
|
|
import {ErrorDialogService, LoggingService} from '@app/_services';
|
|
|
|
import {Router} from '@angular/router';
|
2021-03-15 12:54:46 +01:00
|
|
|
|
|
|
|
@Injectable()
|
|
|
|
export class ErrorInterceptor implements HttpInterceptor {
|
|
|
|
|
2021-03-21 14:11:05 +01:00
|
|
|
constructor(
|
|
|
|
private errorDialogService: ErrorDialogService,
|
|
|
|
private loggingService: LoggingService,
|
|
|
|
private router: Router
|
|
|
|
) {}
|
2021-03-15 12:54:46 +01:00
|
|
|
|
|
|
|
intercept(request: HttpRequest<unknown>, next: HttpHandler): Observable<HttpEvent<unknown>> {
|
2021-03-21 14:11:05 +01:00
|
|
|
return next.handle(request).pipe(
|
|
|
|
catchError((err: HttpErrorResponse) => {
|
|
|
|
let errorMessage;
|
|
|
|
if (err.error instanceof ErrorEvent) {
|
|
|
|
// A client-side or network error occurred. Handle it accordingly.
|
|
|
|
errorMessage = `An error occurred: ${err.error.message}`;
|
|
|
|
} else {
|
|
|
|
// The backend returned an unsuccessful response code.
|
|
|
|
// The response body may contain clues as to what went wrong.
|
|
|
|
errorMessage = `Backend returned code ${err.status}, body was: ${JSON.stringify(err.error)}`;
|
|
|
|
}
|
2021-03-22 14:56:34 +01:00
|
|
|
this.loggingService.sendErrorLevelMessage(errorMessage, this, {error: err});
|
2021-03-21 14:11:05 +01:00
|
|
|
switch (err.status) {
|
|
|
|
case 401: // unauthorized
|
|
|
|
this.router.navigateByUrl('/auth').then();
|
|
|
|
break;
|
|
|
|
case 403: // forbidden
|
2021-04-25 12:32:23 +02:00
|
|
|
alert('Access to resource is not allowed!');
|
2021-03-21 14:11:05 +01:00
|
|
|
break;
|
|
|
|
}
|
|
|
|
// Return an observable with a user-facing error message.
|
|
|
|
return throwError(err);
|
|
|
|
})
|
|
|
|
);
|
2021-03-15 12:54:46 +01:00
|
|
|
}
|
|
|
|
}
|