Created
September 1, 2021 12:55
-
-
Save gesielrosa/ed3a0a0c0a8eb48cdc9ed5642b38a3ab 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 { ErrorHandler, Inject, Injectable, InjectionToken } from '@angular/core'; | |
import { | |
HTTP_INTERCEPTORS, | |
HttpErrorResponse, | |
HttpEvent, | |
HttpHandler, | |
HttpInterceptor, | |
HttpRequest | |
} from '@angular/common/http'; | |
import { Observable, throwError } from 'rxjs'; | |
import { catchError } from 'rxjs/operators'; | |
import * as Rollbar from 'rollbar'; | |
import { environment } from '@env/environment'; | |
/** | |
* Rollbar configs | |
*/ | |
const rollbarConfig = { | |
accessToken: environment.rollbar_token || '', | |
captureUncaught: true, | |
captureUnhandledRejections: true, | |
environment: environment.production ? 'production' : 'development' | |
}; | |
/** | |
* Rollbar error handlers | |
*/ | |
@Injectable() | |
export class RollbarErrorHandler implements ErrorHandler { | |
constructor(@Inject(RollbarService) private rollbar: Rollbar) { | |
} | |
public handleError(err: any): void { | |
this.rollbar.error(err.originalError || err); | |
} | |
} | |
/** | |
* Rollbar factory | |
*/ | |
export function rollbarFactory(): Rollbar { | |
return new Rollbar(rollbarConfig); | |
} | |
/** | |
* Rollbar service | |
*/ | |
export const RollbarService = new InjectionToken<Rollbar>('rollbar'); | |
/** | |
* Rollbar service | |
*/ | |
@Injectable() | |
export class HttpRollbarInterceptor implements HttpInterceptor { | |
/** | |
* Inject dependencies | |
* @constructor | |
* @param rollbar: Rollbar | |
*/ | |
constructor(@Inject(RollbarService) private rollbar: Rollbar) { | |
} | |
/** | |
* Intercept all http requests and response to treat headers | |
* @param req: HttpRequest<any> | |
* @param next: HttpHandler | |
*/ | |
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> { | |
return next.handle(req).pipe(catchError((error) => this.onError(error))); | |
} | |
/** | |
* On Error occurred | |
* @param error: anyø | |
*/ | |
private onError(error) { | |
if (error instanceof HttpErrorResponse) { | |
this.rollbar.error(error.message, error); | |
} | |
return throwError(error); | |
} | |
} | |
/** | |
* Rollbar error handler providers | |
*/ | |
export const ROLLBAR_PROVIDERS = environment.rollbar_token ? [ | |
{provide: HTTP_INTERCEPTORS, useClass: HttpRollbarInterceptor, multi: true}, | |
{provide: ErrorHandler, useClass: RollbarErrorHandler}, | |
{provide: RollbarService, useFactory: rollbarFactory} | |
] : []; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment