Angular 2/4 global error handling

I need to do global error handling in an angular 4 application. This is a mechanism ErrorHandlerthat works in some cases, but not for everyone. Example: when we receive a critical error, for example, a missing template or something else, ErrorHandlerignore it. When I use the wrong url for the template, I get the Zone.js error:

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

Zone.js does not throw an exception, it is just a console error, so window.onerror does not work either.

Error Handler:

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

    }


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

Register in app.module:

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

UPD Added plnkr example:

example

+7
source share
2 answers

Angular zone.js : https://github.com/angular/zone.js/blob/master/dist/zone.js#L633

NgZone : https://angular.io/docs/ts/latest/api/core/index/NgZone-class.html

NgZone API "", , . API "".

:

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);
  }
}

, .

@EDIT: https://angular-2-training-book.rangle.io/handout/zones/ .

+9

, (, ), , , .

try catch 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';
    }
  }
0

All Articles