Search code examples
node.jsangulartypescriptstackblitz

Registering an Angular ErrorHandler?


Tried registering an Angular ErrorHandler in this minimal stackblitz, however it is not logging the error that is thrown in the constructor of the HelloComponent.

Thoughts?


Solution

  • I think the issue here is that by throwing the Error in the constructor of HelloComponent, you're not really allowing the ErrorHandler to get registered.

    If you throw the Error after the Application has bootstrapped properly, probably on a click of a button, then your ErrorHandler should catch it.

    Try this in your AppComponent Template:

    ...
    
    <button (click)="throwError()">Click Me To Generate Error</button>
    

    And in your AppComponent:

    import { Component } from '@angular/core';
    
    @Component({...})
    export class AppComponent  {
      ...
      throwError() {
        throw new Error("This error should be caught by our handler.");
      }
    }
    

    And your HelloComponent:

    import { Component, Input } from '@angular/core';
    
    @Component({...})
    export class HelloComponent  {
      @Input() name: string;
      constructor() {
      }
    }
    

    Here's a Working Sample StackBlitz for your ref.

    enter image description here