Last active
October 13, 2021 08:27
-
-
Save jotatoledo/765c7f6d8a755613cafca97e83313b90 to your computer and use it in GitHub Desktop.
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
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