start of error interceptor

This commit is contained in:
Jesse Lucas 2020-04-06 14:32:27 -04:00
parent 5a6d79a66e
commit b247ef2632
3 changed files with 54 additions and 0 deletions

View File

@ -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();
});
});

View File

@ -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<any>, next: HttpHandler): Observable<HttpEvent<any>> {
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);
})
)
}
}

View File

@ -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 },
];