Last active
September 1, 2017 07:57
AngularJS error handling service to be used in global error handler
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import {BrowserModule} from '@angular/platform-browser'; | |
import {ErrorHandler, Injectable, NgModule} from '@angular/core'; | |
import {HttpErrorResponse} from '@angular/common/http'; | |
import {AppComponent} from './app.component'; | |
// Our service to handle errors (ideally in its own file) | |
@Injectable() | |
export class ErrorLogService { | |
private name: String = 'ErrorLogService'; | |
logError(error: any) { | |
if (error instanceof HttpErrorResponse) { | |
console.error('There was an HTTP error.', error.message, 'Status code:', (<HttpErrorResponse>error).status); | |
} else if (error instanceof TypeError) { | |
console.error('There was a Type error.', error.message); | |
} else if (error instanceof Error) { | |
console.error('There was a general error.', error.message); | |
} else { | |
console.error('Nobody threw an error but something happened!', error); | |
} | |
} | |
} | |
// global error handler that utilizes the above created service (ideally in its own file) | |
@Injectable() | |
export class GlobalErrorHandler extends ErrorHandler { | |
constructor(private errorLogService: ErrorLogService) { | |
super(); | |
} | |
handleError(error) { | |
this.errorLogService.logError(error); | |
} | |
} | |
// register things | |
@NgModule({ | |
declarations: [AppComponent], | |
imports: [BrowserModule], | |
providers: [ | |
// register global error handler | |
GlobalErrorHandler, | |
// register global error log service | |
ErrorLogService | |
], | |
bootstrap: [AppComponent] | |
}) | |
export class AppModule { | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment