Last active
October 15, 2021 00:46
-
-
Save AngelAlexQC/4d11d5522bf772d4602a4d667eb03dea to your computer and use it in GitHub Desktop.
Interceptor for 401 errors
This file contains hidden or 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 { AuthService } from './../services/auth.service'; | |
import { Injectable } from '@angular/core'; | |
import { | |
HttpRequest, | |
HttpHandler, | |
HttpEvent, | |
HttpInterceptor, | |
} from '@angular/common/http'; | |
import { Observable, throwError } from 'rxjs'; | |
import { catchError } from 'rxjs/operators'; | |
@Injectable() | |
export class ErrorInterceptor implements HttpInterceptor { | |
constructor(private authenticationService: AuthService) {} | |
intercept( | |
request: HttpRequest<any>, | |
next: HttpHandler | |
): Observable<HttpEvent<any>> { | |
return next.handle(request).pipe( | |
catchError((err) => { | |
console.log(err); | |
if (err.status === 401) { | |
// auto logout if 401 response returned from api | |
this.authenticationService.logout(); | |
} | |
const error = err.error.messages || err.statusText; | |
return throwError(error); | |
}) | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment