Global error handler in Angular

Global error handler in Angular

It would be nice to have in our applications simple, centralized solution for error management. Fortunately, Angular delivers us a class for handling exceptions.

By default, when unhandled exception occurs during runtime of our application, Angular prints it in console. This behaviour can be overridden by implementing ErrorHandler class declaration from @angular/core.

In example below unhandled errors will be displayed to user in message box.

@Injectable()
export class GlobalErrorHandler implements ErrorHandler {

  constructor(private messageBoxService: MessageBoxService) {
  }

  handleError(error: any): void {
    this.messageBoxService.open(error?.message);
  }
}

To make it work remember to provide your solution to proper module:

@NgModule({
  // ...
  providers: [
    // ...
    { provide: ErrorHandler, useClass: GlobalErrorHandler }
  ]
})
export class AppModule { }