import { HttpErrorResponse , HttpEvent , HttpHandler , HttpInterceptor , HttpRequest , HttpStatusCode , HTTP_INTERCEPTORS } from '@angular/common/http' ; import { Injectable } from '@angular/core' ; import { NavigationExtras , Router } from '@angular/router' ; import { makeFirstLetterLowercase } from '@shared/utils' ; import { ToastrService } from 'ngx-toastr' ; import { Observable , throwError } from 'rxjs' ; import { catchError } from 'rxjs/operators' ; @ Injectable ( ) export class ErrorInterceptor implements HttpInterceptor { constructor ( private toast , private router ) { } intercept ( request , next ) { return next . handle ( request ) . pipe ( catchError ( ( error ) : Observable < never > => { if ( error instanceof HttpErrorResponse ) { const { status } = error ; switch ( status ) { case HttpStatusCode . BadRequest : if ( error . error ?. errors ) { const { errors } = error . error ; const modalStateErrors = [ ] ; for ( const err in errors ) { if ( errors . hasOwnProperty ( err ) ) { modalStateErrors . push ( { [ makeFirstLetterLowercase ( err ) ] : errors [ err ] } ) ; } } return throwError ( ( ) => modalStateErrors ) ; } this . toast . error ( error . error ) ; return throwError ( ( ) => error . error ) ; case HttpStatusCode . NotFound : this . toast . warning ( 'Not found!' , 'Item does not exist!' ) ; return throwError ( ( ) => error ) ; case HttpStatusCode . Unauthorized : this . toast . error ( 'You are not authorized!' ) ; return throwError ( ( ) => error ) ; case HttpStatusCode . InternalServerError : const navigationExtras = { state : { error : error . error } } ; this . router . navigateByUrl ( 'errors/server' , navigationExtras ) ; return throwError ( ( ) => error ) ; default : this . toast . error ( 'Something unexpected went wrong!' ) ; console . log ( error ) ; break ; } } return throwError ( ( ) => error ) ; } ) ) ; } } export const ErrorInterceptorProvider = { provide : HTTP_INTERCEPTORS , useClass : ErrorInterceptor , multi : true } ;