How to handle errors globally?

Viewed 7152

I need to implement global error handling in Angular 4 app. It is ErrorHandler mechanism, that works for some cases, but not for all.

For example, when we got some critical error, like missing template or something, ErrorHandler ignores it. When I use wrong URL for template I get a zone.js error:

zone.js?fad3:567 Unhandled Promise rejection: Template parse errors: 'my-app' is not a known element:

zone.js doesn't throw an exception, but just a console error, so window.onerror doesn't work too.

Error handler:

@Injectable()
export class CommonErrorHandler implements ErrorHandler {
    constructor(private injector: Injector) {
    }


    public handleError(error: any): void {
        console.log("error", error);
    }
}

Registration in app.module:

 providers: [
        AuthGuard,
        { provide: ErrorHandler, useClass: CommonErrorHandler }
}

UPDATE: Plnkr

2 Answers

The accepted solution didn't work for me as my error came at initialization (e.g. a component not declared in module) and since I have a loading animation, I wanted to stop it.

Instead, I encapsulated with a try catch the bootstrapModule code in try/catch

  try {
    platformBrowserDynamic()
      .bootstrapModule(AppModule)
      .catch(err => {
        // Handle runtime error in angular
      });
  } catch (err) {
    // handle angular loading error here. I do that by hidding the animation div and showing the error div

    var node = document.getElementById('app-loading-error');
    if (node) {
      node.style.display = 'inherit';
    }

    var node = document.getElementById('app-loading-pending');
    if (node) {
      node.style.display = 'none';
    }

    throw err; // pass it back to the console
  }
Related