Skip to content

Commit

Permalink
Added error Handling
Browse files Browse the repository at this point in the history
  • Loading branch information
aymanelya committed Jun 22, 2020
1 parent 4e3068b commit ba4b074
Show file tree
Hide file tree
Showing 3 changed files with 58 additions and 2 deletions.
3 changes: 2 additions & 1 deletion src/app/app.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import { NavComponent } from './nav/nav.component';
import { NotfoundComponent } from './notfound/notfound.component';
import { CommunicationService } from './service/communication.service';
import { HomeComponent } from './home/home.component';
import { ErrorInterceptorProvider } from './service/error.interceptor';

@NgModule({
declarations: [
Expand All @@ -30,7 +31,7 @@ import { HomeComponent } from './home/home.component';
AppRoutingModule,
HttpClientModule,
],
providers: [CommunicationService],
providers: [CommunicationService, ErrorInterceptorProvider],
bootstrap: [AppComponent],
})
export class AppModule {}
2 changes: 1 addition & 1 deletion src/app/nav/nav.component.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ export class NavComponent implements OnInit {
console.log('logged in successfully');
},
(error) => {
console.log('Failed to login');
console.log(error);
}
);
}
Expand Down
55 changes: 55 additions & 0 deletions src/app/service/error.interceptor.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
import { Injectable } from '@angular/core';
import {
HttpInterceptor,
HttpErrorResponse,
HTTP_INTERCEPTORS,
} from '@angular/common/http';
import { catchError } from 'rxjs/operators';
import { throwError } from 'rxjs';

@Injectable()
export class ErrorInterceptor implements HttpInterceptor {
intercept(
req: import('@angular/common/http').HttpRequest<any>,
next: import('@angular/common/http').HttpHandler
): import('rxjs').Observable<import('@angular/common/http').HttpEvent<any>> {
return next.handle(req).pipe(
catchError((error) => {
if (error.status === 401) {
return throwError(error.status);
}
if (error instanceof HttpErrorResponse) {
const applicationError = error.headers.get('Application-Error');
if (applicationError) {
return throwError(applicationError);
}

const serverError = JSON.parse(error.error);
let modalStateErrors = '';

if (serverError.errors && typeof serverError.errors === 'object') {
for (const key in serverError.errors) {
if (serverError.errors[key]) {
modalStateErrors += serverError.errors[key] + '\n';
}
}
} else if (serverError[0]) {
for (const index in serverError) {
if (serverError[index]) {
modalStateErrors += serverError[index].description;
}
}
}

return throwError(modalStateErrors || serverError || 'Server Error');
}
})
);
}
}

export const ErrorInterceptorProvider = {
provide: HTTP_INTERCEPTORS,
useClass: ErrorInterceptor,
multi: true,
};

0 comments on commit ba4b074

Please sign in to comment.