2

I am able to catch exceptions when using the subscribe() method with catch(), but this is done on a service call basis.

Is there any way to catch an exception that happens anywhere in the page and display it in the view?

It is straight forward to catch the exceptions and display them in the console, but I need to display something in the view to give a helpful error message as opposed to just freezing.

Thanks

Alexander Abakumov
  • 13,617
  • 16
  • 88
  • 129
Funky
  • 12,890
  • 35
  • 106
  • 161
  • You can use [window.onerror](https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers/onerror) to react to all exceptions on the page, but I'm not sure this is a good idea... – AngularChef Feb 14 '17 at 09:52

1 Answers1

3

You can override the global error handler within your module:

https://angular.io/docs/ts/latest/api/core/index/ErrorHandler-class.html

import { NgModule, ErrorHandler } from '@angular/core';

class MyErrorHandler implements ErrorHandler {
  handleError(error) {
    // do something with the exception
  }
}
@NgModule({
  providers: [{ provide: ErrorHandler, useClass: MyErrorHandler }]
})
class MyModule {}

For a custom Error Dialog or Error Message, I would create a custom ErrorLogService, which allows components to subscribe to an error event. The component that shows the error would subscribe to the error event, and display an error message, or popup an error dialog.

See this answer for how to use Flux to do this (the pattern is important - not the specific classes involved): How can I maintain the state of dialog box with progress all over my Angular 2 application?

Community
  • 1
  • 1
Michael Kang
  • 52,003
  • 16
  • 103
  • 135