Skip to content

Instantly share code, notes, and snippets.

@nicolaisueper
Last active June 9, 2017 10:48
Show Gist options
  • Save nicolaisueper/d7f05b5ae41dc42cffb4b242341f057f to your computer and use it in GitHub Desktop.
Save nicolaisueper/d7f05b5ae41dc42cffb4b242341f057f to your computer and use it in GitHub Desktop.
Centralized Error Handling in Angular

Global error handling in Angular 2 / 4

Create ErrorHandler

// file: my-error-handler.ts

import { ErrorHandler, Injector, Injectable } from '@angular/core';
import { Response } from '@angular/http';
import { Router } from '@angular/router';

@Injectable()
export class MyErrorHandler extends ErrorHandler {

  private router: Router;

  constructor(private inj: Injector) {
    super(false);
    this.router = inj.get(Router); // You may need to do this, because at the time of creation the DI-System isn't up
  }

  handleError(error: any): void {
    if (error instanceof Response) { // You may need to differentiate between several error types
      const err = error as Response;
      if (err.status === 401) { // Token invalid or expired, I'm using JWT
        localStorage.removeItem('id_token');
        this.router.navigate(['/login', 'offline']);
        console.error('Token invalid or expired. Logged out.');
      }
    } else {
      console.error('APPLICATION ERROR: \'' + error.message + '\'');
      console.error(error);
    }
  }
}

Register error handler

// file: app.module.ts
@NgModule({
  declarations: [
   ...
  ],
  imports: [
    ...
  ],
  providers: [
    ...
    { provide: ErrorHandler, useClass: MyErrorHandler } // Override default error handler class, which is the base class of our 'MyErrorHandler'
  ],
  bootstrap: [AppComponent]
})

export class AppModule {
  constructor() {
  }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment