Skip to content

Instantly share code, notes, and snippets.

@llekn
Created August 3, 2018 15:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save llekn/895436cbfae7486cfd93c92f62c5e50e to your computer and use it in GitHub Desktop.
Save llekn/895436cbfae7486cfd93c92f62c5e50e to your computer and use it in GitHub Desktop.
HTTP Logger using Angular's `HttpInterceptor`
import { Injectable } from '@angular/core';
import {
HttpRequest,
HttpHandler,
HttpEvent,
HttpInterceptor,
HttpErrorResponse,
} from '@angular/common/http';
import { EnvConfigurationProvider } from 'gl-ionic2-env-configuration';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/do';
import Raven from 'raven-js';
import { ENVConfig } from '../env-configuration';
@Injectable()
export class HTTPLogger implements HttpInterceptor {
private config: ENVConfig;
constructor(private envConfiguration: EnvConfigurationProvider<ENVConfig>) {
this.config = this.envConfiguration.getConfig();
}
public intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return next.handle(request)
.do(
(event: HttpEvent<any>) => {
if (this.config.logLevel === 'debug' && !request.url.includes('www/assets')) {
Raven.captureMessage(JSON.stringify({ requestData: request }), { level: 'debug' });
}
},
(err: HttpErrorResponse) => {
// Sentry treats HTTPErrorResponse like plain objects
// Let's format them so we can have better info and grouping
let nativeError: Error;
let url: URL;
let urlString: string;
if (err.url && (err.status !== 0)) {
url = new URL(err.url);
urlString = url.origin + url.pathname;
nativeError = new Error(`HTTP error ${err.status} connecting to ${urlString}`);
} else {
try {
// It's really hard to get the original URL if the request fails!
url = new URL(err.error.currentTarget.__zone_symbol__xhrURL);
} catch (e) { }
urlString = url ? url.origin + url.pathname : 'unknown url';
nativeError = new Error(`Network error while trying to connect to ${urlString}`);
}
Raven.captureException(
nativeError,
{
extra: { error: err, isNetworkError: err.status === 0 },
fingerprint: ['{{ default }}', urlString],
},
);
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment