Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.