Skip to content

Instantly share code, notes, and snippets.

@ngnam
Created January 4, 2019 12:13
Show Gist options
  • Save ngnam/d0d4c13d05ba2318ce3b4429439df901 to your computer and use it in GitHub Desktop.
Save ngnam/d0d4c13d05ba2318ce3b4429439df901 to your computer and use it in GitHub Desktop.
error-handler.intercepter.ts
import { Injectable } from '@angular/core';
import {
HttpEvent,
HttpInterceptor,
HttpHandler,
HttpRequest,
HttpResponse
} from '@angular/common/http';
import { Observable } from 'rxjs';
import { catchError } from 'rxjs/operators';
import { environment } from '@env/environment';
import { Logger } from '../logger.service';
import { AuthenticationService } from '..';
import { Router } from '@angular/router';
const log = new Logger('ErrorHandlerInterceptor');
/**
* Adds a default error handler to all requests.
*/
@Injectable()
export class ErrorHandlerInterceptor implements HttpInterceptor {
intercept(
request: HttpRequest<any>,
next: HttpHandler
): Observable<HttpEvent<any>> {
return next
.handle(request)
.pipe(catchError(error => this.errorHandler(error)));
}
// Customize the default error handler here if needed
private errorHandler(response: HttpEvent<any>): Observable<HttpEvent<any>> {
if (!environment.production) {
// Do something with the error
log.error('Request error');
log.error(response);
}
// unAuthentication
if (response instanceof HttpResponse) {
if (response.status === 401) {
this.authenticationService
.logout()
.subscribe(() =>
this.router.navigate(['/login'], { replaceUrl: true })
);
}
// swich case with status 500, 404, ...
}
throw response;
}
constructor(
private authenticationService: AuthenticationService,
private router: Router
) {}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment