error handler interceptor

 import { Injectable } from '@angular/core';

import {
  HttpRequest,
  HttpHandler,
  HttpEvent,
  HttpInterceptor
} from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import { catchError } from 'rxjs/operators';
import { LoginService } from '../Services/login.service';

@Injectable()
export class ErrorInterceptor implements HttpInterceptor {

  constructor(private loginService:LoginService) {}

  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    return next.handle(request).pipe(catchError(err => {
        if ([401, 403].indexOf(err.status) !== -1) {
            // auto logout if 401 Unauthorized or 403 Forbidden response returned from api
            this.loginService.logout();
           // location.reload(true);
        }

        //const error = err.error.message || err.statusText;
        const error = err.status;
        return throwError(error);
    }))
}
}





app.module.ts
----------------
providers: [
               { provide: HTTP_INTERCEPTORS, useClass: ErrorInterceptor, multi: true },],


Comments