Skip to content

Instantly share code, notes, and snippets.

@davestacey
Created February 21, 2020 14:37
Show Gist options
  • Save davestacey/7dc11e9460c28f01b376d7a962a21a9b to your computer and use it in GitHub Desktop.
Save davestacey/7dc11e9460c28f01b376d7a962a21a9b to your computer and use it in GitHub Desktop.
Http Error Interceptor
/*
The Error Interceptor intercepts http responses from the api to check if there were any errors.
If there is a 401 Unauthorized response the user is automatically logged out of the application, all other errors are re-thrown up to the calling service so an alert can be displayed to the user.
*/
import { Injectable } from '@angular/core';
import { HttpRequest, HttpHandler, HttpEvent, HttpInterceptor } from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import { catchError } from 'rxjs/operators';
import { AuthenticationService } from '@/_services';
@Injectable()
export class ErrorInterceptor implements HttpInterceptor {
constructor(private authenticationService: AuthenticationService) {}
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return next.handle(request).pipe(catchError(err => {
if (err.status === 401) {
// auto logout if 401 response returned from api
this.authenticationService.logout();
location.reload(true);
}
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