Last active
May 2, 2021 17:36
-
-
Save walidum/6c0963bc11d1fb30e1102d371defb24b to your computer and use it in GitHub Desktop.
error.interceptor.ts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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