John Doe
John Doe

Reputation: 139

How to handle errors globally?

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

Upvotes: 8

Views: 7837

Answers (2)

Jeremy
Jeremy

Reputation: 1002

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
  }

Upvotes: 0

rzelek
rzelek

Reputation: 4013

Angular uses zone.js to parse unhandled exceptions and rejections: https://github.com/angular/zone.js/blob/master/dist/zone.js#L633

You need to use NgZone service to parse these errors: https://angular.io/docs/ts/latest/api/core/index/NgZone-class.html

NgZone API is marked as an "experimental" but I do not know how it relates to reality. Bunch of widely used APIs are still "experimental".

Example:

import { NgZone } from '@angular/core';

@Component(...)
class AppComponent {
  constructor(protected zone: NgZone) {

    this.zone.onError.subscribe((e) => {
      console.log(e);
    });

    setTimeout(() => {
      throw new Error();
    }, 1000);

    setTimeout(() => {
      Promise.reject('unhandled');
    }, 1000);
  }
}

This way you can see both of the errors.

@EDIT: I found this https://angular-2-training-book.rangle.io/handout/zones/ very useful.

Upvotes: 11

Related Questions