Created
January 31, 2018 10:06
-
-
Save code-atom/88ef20d1a4c79120a4f3333b7fb7cb9b to your computer and use it in GitHub Desktop.
Setup Custom Global Error Handler in angular
This file contains hidden or 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 { BrowserAnimationsModule } from '@angular/platform-browser/animations'; | |
import { NgModule, ErrorHandler } from '@angular/core'; | |
import { ToastrModule, ToastContainerModule } from 'ngx-toastr'; | |
import { AppRoutingModule } from './app.routing.module'; | |
import { CoreModule } from './core/core.module'; | |
import { AppComponent } from './app.component'; | |
import { GlobalErrorHandler } from './error-handler.service'; | |
import { AppRootLoaderComponent } from './content-loader.component'; | |
import { AppService } from './app.service'; | |
@NgModule({ | |
declarations: [ | |
AppComponent, | |
AppRootLoaderComponent | |
], | |
imports: [ | |
BrowserModule, | |
CoreModule.forRoot(), | |
BrowserAnimationsModule, | |
ToastrModule.forRoot(), | |
ToastContainerModule, | |
AppRoutingModule | |
], | |
providers: [ | |
{ | |
provide: ErrorHandler, | |
useClass: GlobalErrorHandler | |
}, | |
AppService | |
], | |
bootstrap: [AppComponent] | |
}) | |
export class AppModule { } |
This file contains hidden or 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 { ErrorHandler, Injectable, Injector, NgZone } from "@angular/core"; | |
import { StackTrace } from 'stacktrace-js'; | |
import { ToastrService } from "ngx-toastr"; | |
import { Router } from "@angular/router"; | |
import { AuthService } from "./core/auth.service"; | |
import { AuthenticationException } from "./core/exceptions"; | |
@Injectable() | |
export class GlobalErrorHandler extends ErrorHandler { | |
constructor(private injector: Injector, private zone: NgZone) { | |
super(false); | |
} | |
handleError(error) { | |
var toastService = this.injector.get(ToastrService); | |
var router = this.injector.get(Router); | |
var authService = this.injector.get(AuthService); | |
if (error instanceof AuthenticationException || error.rejection instanceof AuthenticationException) { | |
this.zone.run(() => { | |
authService.logout(); | |
toastService.info('Your session has been expired'); | |
router.navigateByUrl('/auth'); | |
}); | |
} else { | |
super.handleError(error); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment