Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle errors globally?

Tags:

angular

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

like image 803
John Doe Avatar asked Jun 02 '17 08:06

John Doe


Video Answer


1 Answers

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.

like image 90
rzelek Avatar answered Sep 30 '22 18:09

rzelek