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