Skip to content

Instantly share code, notes, and snippets.

@nicolaisueper
Last active Jun 9, 2017
Embed
What would you like to do?
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