error.interceptor.ts 2.04 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
import { HttpErrorResponse, HttpEvent, HttpHandler, HttpInterceptor, HttpRequest } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable, throwError } from 'rxjs';
import { catchError } from 'rxjs/operators';
import { AnalyticsService } from '../analytics.service';

const X_REQUEST_ID = 'x-request-id';

@Injectable({ providedIn: 'root' })
export class ErrorStatusInterceptor implements HttpInterceptor {
  constructor(private aService: AnalyticsService) {}

  public intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    return next.handle(request).pipe(
      catchError((error: HttpErrorResponse) => {
        let errorMsg = 'not provided';

        // capture the request ID either from the error response or the original request
        let xRequestId = '';
        if (error.headers.has(X_REQUEST_ID)) {
          xRequestId = error.headers.get(X_REQUEST_ID);
        } else if (request.headers.has(X_REQUEST_ID)) {
          xRequestId = request.headers.get(X_REQUEST_ID);
        }

        if (error.error && error.error.errorMessage) {
          errorMsg = error.error.errorMessage;
        }

        // there are 2 possible types of errors: client side and server side HTTP errors
        // CORS errors fall into client side errors, they will have ErrorCode 0 in chrome and you will not see the real response code.
        if (error.error instanceof ErrorEvent) {
          // client error
          errorMsg = `Client/Network Error: ${error.error.type} -> ${error.error.message}`;
        } else {
          // server error, pull out HTTP response status and message
          errorMsg = `HTTP ${error.status}: ${error.statusText}, message: [${errorMsg}]`;
        }

        this.aService.recordError(
          `${errorMsg} time: [${new Date().toISOString()}] from [${error.url}] requestMethod: ${
            request.method
          } fullRequestUrl: ${request.urlWithParams} ${!!xRequestId ? `xRequestId: ${xRequestId}` : ''}`
        );
        return throwError(error);
      })
    );
  }
}