Skip to content

Instantly share code, notes, and snippets.

@AngelAlexQC
Last active October 15, 2021 00:46
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AngelAlexQC/4d11d5522bf772d4602a4d667eb03dea to your computer and use it in GitHub Desktop.
Save AngelAlexQC/4d11d5522bf772d4602a4d667eb03dea to your computer and use it in GitHub Desktop.
Interceptor for 401 errors
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