Skip to content

Instantly share code, notes, and snippets.

@code-atom
Created January 31, 2018 10:06
Show Gist options
  • Save code-atom/88ef20d1a4c79120a4f3333b7fb7cb9b to your computer and use it in GitHub Desktop.
Save code-atom/88ef20d1a4c79120a4f3333b7fb7cb9b to your computer and use it in GitHub Desktop.
Setup Custom Global Error Handler in angular
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 { }
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