1import { HttpEvent, HttpInterceptor, HttpHandler, HttpRequest, HttpErrorResponse } from '@angular/common/http';
2import { Observable, throwError } from 'rxjs';
3import { catchError } from 'rxjs/operators';
4export class HttpErrorInterceptor implements HttpInterceptor {
5 intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
6 return next.handle(request)
7 .pipe(
8 catchError((error: HttpErrorResponse) => {
9 let errorMsg = '';
10 if (error.error instanceof ErrorEvent) {
11 console.log('this is client side error');
12 errorMsg = `Error: ${error.error.message}`;
13 }
14 else {
15 console.log('this is server side error');
16 errorMsg = `Error Code: ${error.status}, Message: ${error.message}`;
17 }
18 console.log(errorMsg);
19 return throwError(errorMsg);
20 })
21 )
22 }
23}
1// src/app/auth/jwt.interceptor.ts
2
3// ...
4import 'rxjs/add/operator/do';
5
6export class JwtInterceptor implements HttpInterceptor {
7
8 constructor(public auth: AuthService) {}
9
10 intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
11
12 return next.handle(req).do((event: HttpEvent<any>) => {
13 if (event instanceof HttpResponse) {
14 // do stuff with response if you want
15 }
16 }, (err: any) => {
17 if (err instanceof HttpErrorResponse {
18 if (err.status === 401) {
19 // redirect to the login route
20 // or show a modal
21 }
22 }
23 });
24 }
25}
26