All files / src/app/core/interceptors icm-error-mapper.interceptor.ts

90.38% Statements 47/52
83.33% Branches 30/36
88.88% Functions 8/9
91.66% Lines 44/48

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148  1x 1x 1x 1x                     1x     1x   11x 11x         11x 11x   11x         11x 1x     10x 1x     9x 1x 1x 1x   1x           8x 1x           7x 1x           6x   6x                 2x 2x 2x 2x 1x     2x       1x           4x               2x 2x 2x 2x         2x                     2x                       11x   11x     11x 11x              
import { HttpErrorResponse, HttpEvent, HttpHandler, HttpInterceptor, HttpRequest } from '@angular/common/http';
import { ErrorHandler, Injectable, InjectionToken, Injector } from '@angular/core';
import { pick } from 'lodash-es';
import { Observable, throwError } from 'rxjs';
import { catchError } from 'rxjs/operators';
 
import { HttpError } from 'ish-core/models/http-error/http-error.model';
 
/* eslint-disable @typescript-eslint/no-restricted-types */
 
export interface SpecialHttpErrorHandler {
  test(error: HttpErrorResponse, request: HttpRequest<unknown>): boolean;
  map(error: HttpErrorResponse, request: HttpRequest<unknown>): Partial<HttpError>;
}
 
export const SPECIAL_HTTP_ERROR_HANDLER = new InjectionToken<SpecialHttpErrorHandler>('specialHttpErrorHandler');
 
@Injectable()
export class ICMErrorMapperInterceptor implements HttpInterceptor {
  constructor(
    private injector: Injector,
    private errorHandler: ErrorHandler
  ) {}
 
  // eslint-disable-next-line complexity
  private mapError(httpError: HttpErrorResponse, request: HttpRequest<unknown>): HttpError {
    const specialHandlers = this.injector.get<SpecialHttpErrorHandler[]>(SPECIAL_HTTP_ERROR_HANDLER, []);
    const specialHandler = specialHandlers.find(handler => handler.test(httpError, request));
 
    const responseError: HttpError = {
      name: 'HttpErrorResponse',
      status: httpError.status,
    };
 
    if (specialHandler) {
      return { name: 'HttpErrorResponse', status: httpError.status, ...specialHandler.map(httpError, request) };
    }
 
    if (httpError.headers?.get('error-type') === 'error-missing-attributes') {
      return { ...responseError, message: httpError.error };
    }
 
    if (httpError.headers?.get('error-type') === 'error-invalid-attributes') {
      let message = httpError.error;
      Eif (typeof request.body === 'object') {
        message += JSON.stringify(pick(request.body, httpError.headers?.get('error-invalid-attributes').split(',')));
      }
      return {
        ...responseError,
        message,
      };
    }
 
    if (httpError.headers?.get('error-key')) {
      return {
        ...responseError,
        code: httpError.headers.get('error-key'),
      };
    }
 
    if (typeof httpError.error === 'string') {
      return {
        ...responseError,
        message: httpError.error,
      };
    }
 
    Eif (typeof httpError.error === 'object') {
      // handle error objects with multiple errors
      if (httpError.error?.errors?.length) {
        const errors: {
          code: string;
          message: string;
          causes?: {
            code: string;
            message: string;
            paths: string[];
          }[];
        }[] = httpError.error.errors;
        Eif (errors.length === 1) {
          const error = errors[0];
          if (error.causes?.length) {
            return {
              ...responseError,
              errors: httpError.error?.errors,
              message: [error.message].concat(...error.causes.map(c => c.message)).join(' '),
            };
          }
        }
        return {
          ...responseError,
          errors: httpError.error?.errors,
        };
      }
      // new ADR error format with messages array
      else if (httpError.error?.messages?.length) {
        const errors: {
          code: string;
          message?: string;
          causes?: {
            code: string;
            message: string;
          }[];
        }[] = httpError.error?.messages;
        Eif (errors.length > 0) {
          const error = errors[0];
          return {
            ...responseError,
            errors: httpError.error.messages,
            // if there are causes, concatenate the main message with the causes messages, otherwise use the main message
            message: (error.message ? '<div>'.concat(error.message).concat('</div>') : '').concat(
              error.causes?.length ? error.causes.map(c => '<div>'.concat(c.message).concat('</div>')).join('') : ''
            ),
          };
        }
        return {
          ...responseError,
          errors: httpError.error?.errors,
        };
      }
 
      // handle all other error responses with error object
      return {
        ...responseError,
        code: httpError.error?.code || httpError.statusText,
        message: httpError.error?.message || httpError.message,
      };
    }
 
    // handle error responses without error object
    return pick(httpError, 'name', 'status', 'message');
  }
 
  intercept(req: HttpRequest<unknown>, next: HttpHandler): Observable<HttpEvent<unknown>> {
    return next.handle(req).pipe(
      catchError((error: HttpErrorResponse) => {
        Iif (SSR) {
          this.errorHandler.handleError(error);
        }
        Eif (error.name === 'HttpErrorResponse') {
          return throwError(() => this.mapError(error, req));
        }
        return throwError(() => error);
      })
    );
  }
}