import { HttpErrorResponse , HttpEvent , HttpHandler , HttpInterceptor , HttpRequest , HTTP_INTERCEPTORS } from '@angular/common/http' ; import { Injectable , NgModule } from '@angular/core' ; import { MatSnackBar } from '@angular/material' ; import { Router } from '@angular/router' ; import { Observable } from 'rxjs' ; import { tap } from 'rxjs/operators' ; @ Injectable ( ) export class ErrorHttpInterceptor implements HttpInterceptor { param router param snackBar constructor ( private router , private snackBar ) { } param req param next intercept ( req , next ) { return next . handle ( req ) . pipe ( tap ( undefined , ( error ) => { if ( error instanceof HttpErrorResponse ) { let message = '' ; switch ( error . status ) { case 401 : case 403 : message = 'Permission denied. Please try again.' ; break ; case 404 : message = 'Not found. Please try again.' ; break ; default : this . snackBar . open ( error . message , undefined , { duration : 5000 } ) ; break ; } this . router . navigate ( [ '/' ] ) . then ( ( ) => this . snackBar . open ( message , undefined , { duration : 5000 } ) ) ; } } ) ) ; } } @ NgModule ( { providers : [ { provide : HTTP_INTERCEPTORS , useClass : ErrorHttpInterceptor , multi : true , } , ] , } ) export class ErrorHttpInterceptorModule { }