3

Goal

Catch every error of the application in a custom Angular exception handler and then display the errors to the user in a component template.

Problem

The app component subscribes to the exception handler correctly and the exception handler emits the event properly, but the callback function is never called (error=>this.errorMessage=error.message in this case).

main.ts

@Injector();
class MyExceptionHandler implements ExceptionHandler {
  errorOccured: EventEmitter<{}> = new EventEmitter(); 

  call(error, stackTrace = null, reason = null) {
    errorOccured.emit(error);
  }
}
bootstrap(MyAppComponent, {provide: ExceptionHandler, useClass: MyExceptionHandler}])

app.component.ts

 import { Component } from '@angular/core';
    @Component({
      selector: 'my-app',
      template: `
          <p *ngIf="errorMessage">{{errorMessage}}</p>
          <button (click)="triggerError()">Trigger Error></button>`
    })
    export class AppComponent { 
        errorMessage: string;

        constructor(private errorHandler: MyExceptionHandler ) {
            this.errorHandler.errorOccured
                .subscribe(error => this.errorMessage = error.message)
        }

        triggerError() {
            throw new Error('some error');
        }
    }
Community
  • 1
  • 1
Maxime Gélinas
  • 2,202
  • 2
  • 18
  • 35
  • 1
    The `ExceptionHandler` is only a last resort, it doesn't work for catching all errors and continue normally. Exceptions are supposed to be handled as closely as possible to where they are thrown. See also http://stackoverflow.com/a/37793791/217408, https://github.com/angular/angular/issues/8993 – Günter Zöchbauer Jun 29 '16 at 04:05

0 Answers0