As the title says, I am needing to capture all the errors generated in JavaScript but through angular.
The idea is to create a service that sends the errors that occur on the client side to have a log of errors on the server, in order to correct them later.
If it were JavaScript, only things like
window.onerror = MyErrorHandler()
In angular there is a class ErrorHandler
that can be extended but it only catches the errors that are generated in angular.
I need to capture all of them no matter how insignificant they may be.
With Angular 2 , Typescript was introduced as the most suitable language to write an application with Angular 2. Being the case, one can practically eliminate the most trivial javascript errors by activating Ahead of Time compilation .
If you are using the @angular/cli this is done via the aot=true parameter.
For example:
And in our component's view:
If we compile our app the traditional way (aot=false) we don't get any errors until we use our app's button, but if we compile with the Ahead of Time build we'll get the following:
for most errors
You can use the class
ErrorHandler
to@angular/core
handle almost any error that arises during the execution of our Angular 2 application by overriding thehandleError(error:Error):void
. It is worth mentioning that I use this class precisely to send errors from the client side to a server (Raygun) :)For example, to display errors as notifications:
And finally you register it at your application level:
Reference: https://angular.io/docs/ts/latest/api/core/index/ErrorHandler-class.html
If you want to go further
We can hack Zone.js to catch errors that occur when running in that context by inserting the following snippet into our application's index.html .
Reference: https://github.com/angular/zone.js