All files / src/app/core/interceptors error.interceptor.ts

72.22% Statements 13/18
20% Branches 1/5
66.66% Functions 4/6
90.9% Lines 10/11

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 352x 2x             2x 2x 2x             2x 5x     5x         3x 3x              
import { Injectable } from '@angular/core';
import {
  HttpRequest,
  HttpHandler,
  HttpEvent,
  HttpInterceptor,
  HttpErrorResponse
} from '@angular/common/http';
import { catchError, Observable } from 'rxjs';
import { ApiError } from '@core/errors/api-error';
import { ErrorProcessorService } from '@core/services/error-processor.service';
 
/**
 * Intercepts http errors to rethrow structured ApiError
 */
 
@Injectable()
export class ErrorInterceptor implements HttpInterceptor {
  constructor(private errorProcessorService: ErrorProcessorService) {}
 
  intercept(request: HttpRequest<unknown>, next: HttpHandler): Observable<HttpEvent<unknown>> {
    return next.handle(request)
      .pipe(
        // at this point, errors can be "native" HttpErrorResponse or ApiError already created by this ErrorInterceptor
        catchError((error: HttpErrorResponse | ApiError) => {
          // Handle the error
          if(error instanceof HttpErrorResponse) {
            return this.errorProcessorService.processError(new ApiError(error));
          }
          return this.errorProcessorService.processError(error);
        })
      );
  }
}