Created
February 21, 2020 14:37
-
-
Save davestacey/7dc11e9460c28f01b376d7a962a21a9b to your computer and use it in GitHub Desktop.
Http Error Interceptor
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
/* | |
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