diff --git a/projects/nshmp-apps/src/main.ts b/projects/nshmp-apps/src/main.ts index c5e4a2adcfeee9b74e88dd43364ccf4e1f9951cf..4f81ffd98a32167fd0b446282440e792aab03267 100644 --- a/projects/nshmp-apps/src/main.ts +++ b/projects/nshmp-apps/src/main.ts @@ -1,4 +1,4 @@ -import {provideHttpClient} from '@angular/common/http'; +import {provideHttpClient, withInterceptors} from '@angular/common/http'; import {enableProdMode, importProvidersFrom} from '@angular/core'; import {bootstrapApplication, BrowserModule} from '@angular/platform-browser'; import {provideAnimations} from '@angular/platform-browser/animations'; @@ -7,6 +7,7 @@ import {provideRouter} from '@angular/router'; import {AppComponent} from './app/app.component'; import {appRoutes} from './app/app.routes'; import {environment} from './environments/environment'; +import {httpErrorInterceptor} from './shared/interceptors/http-error.interceptor'; if (environment.production) { enableProdMode(); @@ -17,6 +18,6 @@ bootstrapApplication(AppComponent, { importProvidersFrom(BrowserModule), provideRouter(appRoutes()), provideAnimations(), - provideHttpClient(), + provideHttpClient(withInterceptors([httpErrorInterceptor])), ], }).catch(err => console.error(err)); diff --git a/projects/nshmp-apps/src/shared/interceptors/http-error.interceptor.ts b/projects/nshmp-apps/src/shared/interceptors/http-error.interceptor.ts new file mode 100644 index 0000000000000000000000000000000000000000..1de70ea4564de7122b6d235f92a7a200d0be89ce --- /dev/null +++ b/projects/nshmp-apps/src/shared/interceptors/http-error.interceptor.ts @@ -0,0 +1,25 @@ +import { + HttpErrorResponse, + HttpEvent, + HttpHandlerFn, + HttpRequest, +} from '@angular/common/http'; +import {catchError, Observable} from 'rxjs'; + +export function httpErrorInterceptor( + req: HttpRequest<unknown>, + next: HttpHandlerFn +): Observable<HttpEvent<unknown>> { + return next(req).pipe( + catchError(error => { + if ( + error instanceof HttpErrorResponse && + typeof error.error === 'string' + ) { + throw new Error(error.error); + } + + throw error; + }) + ); +}