Skip to content

Instantly share code, notes, and snippets.

@jotatoledo
Last active October 13, 2021 08:27
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save jotatoledo/765c7f6d8a755613cafca97e83313b90 to your computer and use it in GitHub Desktop.
Save jotatoledo/765c7f6d8a755613cafca97e83313b90 to your computer and use it in GitHub Desktop.
import { Injectable, ClassProvider } from '@angular/core';
import { HttpEvent, HttpInterceptor, HttpHandler, HttpRequest, HttpErrorResponse, HTTP_INTERCEPTORS } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import { _throw } from 'rxjs/observable/throw';
import 'rxjs/add/operator/catch';
/**
* Intercepts the HTTP responses, and in case that an error/exception is thrown, handles it
* and extract the relevant information of it.
*/
@Injectable()
export class ErrorInterceptor implements HttpInterceptor {
/**
* Intercepts an outgoing HTTP request, executes it and handles any error that could be triggered in execution.
* @see HttpInterceptor
* @param req the outgoing HTTP request
* @param next a HTTP request handler
*/
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return next.handle(req)
.catch(errorReponse => {
let errMsg: string;
if (errorReponse instanceof HttpErrorResponse) {
const err = errorReponse.message || JSON.stringify(errorReponse.error);
errMsg = `${errorReponse.status} - ${errorReponse.statusText || ''} Details: ${err}`;
} else {
errMsg = errorReponse.message ? errorReponse.message : errorReponse.toString();
}
return _throw(errMsg);
});
}
}
/**
* Provider POJO for the interceptor
*/
export const ErrorInterceptorProvider : ClassProvider = {
provide: HTTP_INTERCEPTORS,
useClass: ErrorInterceptor,
multi: true,
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment