Skip to content

Instantly share code, notes, and snippets.

@walidum
Last active May 2, 2021 17:36
Show Gist options
  • Save walidum/6c0963bc11d1fb30e1102d371defb24b to your computer and use it in GitHub Desktop.
Save walidum/6c0963bc11d1fb30e1102d371defb24b to your computer and use it in GitHub Desktop.
error.interceptor.ts
import { Injectable } from '@angular/core';
import {
HttpRequest,
HttpHandler,
HttpEvent,
HttpInterceptor
} from '@angular/common/http';
import {Observable, throwError} from 'rxjs';
import { AuthenticationService } from '@app/_services';
import {catchError} from 'rxjs/operators';
import {Router} from '@angular/router';
import Swal from 'sweetalert2';
@Injectable()
export class ErrorInterceptor implements HttpInterceptor {
constructor(private service: AuthenticationService, private router: Router, ) {}
intercept(request: HttpRequest<unknown>, next: HttpHandler): Observable<HttpEvent<unknown>> {
return next.handle(request).pipe(catchError(err => {
if (err.status === 401 || err.status === 403) {
this.service.logout();
Swal.fire('Session timed out !', '', 'error').then(ok => {
if (ok.isConfirmed){
this.router.navigate(['login']);
}
});
}
const error = err.error.message || err.statusText;
return throwError(error);
}));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment