diff --git a/src/app/http-interceptors/error.interceptor.spec.ts b/src/app/http-interceptors/error.interceptor.spec.ts new file mode 100644 index 000000000..4d083ad20 --- /dev/null +++ b/src/app/http-interceptors/error.interceptor.spec.ts @@ -0,0 +1,16 @@ +import { TestBed } from '@angular/core/testing'; + +import { ErrorInterceptor } from './error.interceptor'; + +describe('ErrorInterceptor', () => { + beforeEach(() => TestBed.configureTestingModule({ + providers: [ + ErrorInterceptor + ] + })); + + it('should be created', () => { + const interceptor: ErrorInterceptor = TestBed.inject(ErrorInterceptor); + expect(interceptor).toBeTruthy(); + }); +}); diff --git a/src/app/http-interceptors/error.interceptor.ts b/src/app/http-interceptors/error.interceptor.ts new file mode 100644 index 000000000..31288b613 --- /dev/null +++ b/src/app/http-interceptors/error.interceptor.ts @@ -0,0 +1,36 @@ +import { Injectable } from '@angular/core'; +import { + HttpRequest, + HttpHandler, + HttpEvent, + HttpInterceptor, + HttpErrorResponse +} from '@angular/common/http'; +import { Observable, throwError } from 'rxjs'; +import { apiRetry } from '../api-utils'; +import { retry, catchError } from 'rxjs/operators'; + +@Injectable() +export class ErrorInterceptor implements HttpInterceptor { + + constructor() { } + + intercept(request: HttpRequest, next: HttpHandler): Observable> { + return next.handle(request) + .pipe( + retry(apiRetry), + catchError((error: HttpErrorResponse) => { + let errorMsg: string; + if (error.error instanceof ErrorEvent) { + // Client side + errorMsg = `Error: ${error.error.message}`; + } else { + // Server side + errorMsg = `Error Status: ${error.status}\nMessage: ${error.message}`; + } + console.log(errorMsg); + return throwError(errorMsg); + }) + ) + } +} diff --git a/src/app/http-interceptors/index.ts b/src/app/http-interceptors/index.ts index 53635a917..f478c61e6 100644 --- a/src/app/http-interceptors/index.ts +++ b/src/app/http-interceptors/index.ts @@ -3,10 +3,12 @@ import { HTTP_INTERCEPTORS } from '@angular/common/http'; import { CSRFInterceptor } from './csrf.interceptor'; import { CachingInterceptor } from './caching.interceptor'; +import { ErrorInterceptor } from './error.interceptor'; /** Http interceptor providers in outside-in order */ export const httpInterceptorProviders = [ { provide: HTTP_INTERCEPTORS, useClass: CachingInterceptor, multi: true }, + { provide: HTTP_INTERCEPTORS, useClass: ErrorInterceptor, multi: true }, // CSRFInterceptor needs to be last { provide: HTTP_INTERCEPTORS, useClass: CSRFInterceptor, multi: true }, ]; \ No newline at end of file