diff --git a/Client/src/app/app.module.ts b/Client/src/app/app.module.ts index af27583..29fc44f 100644 --- a/Client/src/app/app.module.ts +++ b/Client/src/app/app.module.ts @@ -8,6 +8,7 @@ import { NavMenuComponent } from './components/nav-menu/nav-menu.component'; import { AuthService } from './services/auth.service'; import { HomeComponent } from './components/home/home.component'; import { RegisterComponent } from './components/register/register.component'; +import { ErrorInterceptorProvider } from './services/error.interceptor'; @NgModule({ declarations: [ @@ -22,7 +23,8 @@ import { RegisterComponent } from './components/register/register.component'; FormsModule ], providers: [ - AuthService + AuthService, + ErrorInterceptorProvider ], bootstrap: [AppComponent] }) diff --git a/Client/src/app/components/nav-menu/nav-menu.component.ts b/Client/src/app/components/nav-menu/nav-menu.component.ts index c86e6ea..2c2941a 100644 --- a/Client/src/app/components/nav-menu/nav-menu.component.ts +++ b/Client/src/app/components/nav-menu/nav-menu.component.ts @@ -18,7 +18,7 @@ export class NavMenuComponent implements OnInit { this.authService.login(this.model).subscribe(next => { console.log('logged in') }, error => { - console.log('login failed') + console.log(error) }); } diff --git a/Client/src/app/services/error.interceptor.ts b/Client/src/app/services/error.interceptor.ts new file mode 100644 index 0000000..b8e05b8 --- /dev/null +++ b/Client/src/app/services/error.interceptor.ts @@ -0,0 +1,45 @@ +import { Injectable } from "@angular/core"; +import { HttpInterceptor, HttpHandler, HttpEvent, HttpErrorResponse, HttpRequest, HTTP_INTERCEPTORS } from "@angular/common/http"; +import { Observable, throwError } from "rxjs"; +import { catchError } from "rxjs/operators"; + +@Injectable() +export class ErrorInterceptor implements HttpInterceptor { + intercept(req: HttpRequest, next: HttpHandler): Observable> { + return next.handle(req).pipe( + catchError(error => { + if (error instanceof HttpErrorResponse) { + + if (error.status === 401) { + return throwError(error.statusText); + } + + const applicationError = error.headers.get('Application-Error'); + + if (applicationError) { + return throwError(applicationError); + } + + const serverError = error.error; + let modelStateErrors = ''; + + if (serverError && typeof serverError === 'object') { + for (const key in serverError) { + if (serverError[key]) { + modelStateErrors += `${serverError[key]}\n`; + } + } + + return throwError(modelStateErrors || serverError || 'Server Error'); + } + } + })); + } + +} + +export const ErrorInterceptorProvider = { + provide: HTTP_INTERCEPTORS, + useClass: ErrorInterceptor, + multi: true +} diff --git a/Friendster.csproj b/Friendster.csproj index 5b563cb..27105b7 100644 --- a/Friendster.csproj +++ b/Friendster.csproj @@ -6,7 +6,6 @@ -