File

src/app/_interceptors/error.interceptor.ts

Index

Methods

Constructor

constructor(errorDialogService: ErrorDialogService, loggingService: LoggingService, router: Router)
Parameters :
Name Type Optional
errorDialogService ErrorDialogService No
loggingService LoggingService No
router Router No

Methods

intercept
intercept(request: HttpRequest, next: HttpHandler)
Parameters :
Name Type Optional
request HttpRequest<unknown> No
next HttpHandler No
Returns : Observable<HttpEvent<unknown>>
import {Injectable} from '@angular/core';
import {
  HttpRequest,
  HttpHandler,
  HttpEvent,
  HttpInterceptor, HttpErrorResponse
} from '@angular/common/http';
import {Observable, throwError} from 'rxjs';
import {catchError} from 'rxjs/operators';
import {ErrorDialogService, LoggingService} from '@app/_services';
import {Router} from '@angular/router';

@Injectable()
export class ErrorInterceptor implements HttpInterceptor {

  constructor(
    private errorDialogService: ErrorDialogService,
    private loggingService: LoggingService,
    private router: Router
  ) {}

  intercept(request: HttpRequest<unknown>, next: HttpHandler): Observable<HttpEvent<unknown>> {
    return next.handle(request).pipe(
      catchError((err: HttpErrorResponse) => {
        let errorMessage: string;
        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)}`;
        }
        this.loggingService.sendErrorLevelMessage(errorMessage, this, {error: err});
        switch (err.status) {
          case 401:  // unauthorized
            this.router.navigateByUrl('/auth').then();
            break;
          case 403: // forbidden
            alert('Access to resource is not allowed!');
            break;
        }
        // Return an observable with a user-facing error message.
        return throwError(err);
      })
    );
  }
}

result-matching ""

    No results matching ""