Wednesday, August 9, 2017

Angular  —  Exception Handling Mechanism

One of the main issue which i came across with angular  was exception handling.  When you are developing an application, you are in full control, and you will be able to see the errors and handle them accordingly.
But as you soon deploy it in the production,  you can’t see what your user is seeing and experiencing and you not capable of knowing about errors unless you find a way to be notified about the exceptions.
This solution i have implemented recently and it worked pretty well. Angular 2 has his own way to catch and handle errors. The default implementation of ErrorHandler prints errors messages to the console. You can intercept the default error handling and write a custom exception handler that replaces this default as appropriate for your app.
If you have a production server and you want to send the errors to the server, Let’s see how we can do it.

you need to create your own ErrorHandler class that implements the default ErrorHandler. The only method that required is the handleError method that takes the error as an argument.

 import { ErrorHandler } from '@angular/core';  
 export default class MyErrorHandler implements ErrorHandler {  
   handleError(error) {  
    // send the error to the server  
   }  
 }  


The next step you can go is to change your injector to use your implementation instead of the default. So code will be something like this,

 import { ErrorHandler } from '@angular/core';  
 export default class MyErrorHandler implements ErrorHandler {  
   handleError(error) {  
    // send the error to the server  
   }  
 }  

That’s all folks. If you don’t want to ignore the Angular default handler, you can extend the ErrorHandler class and also call the default handler like this:

 import { ErrorHandler } from '@angular/core';  
 export default class MyErrorHandler implements ErrorHandler {  
   handleError(error) {  
    // send the error to the server  
   }  
 }  

That's it guys!. You can apply this method on your application and make it error free on production. 
You can check the sample on plunker and play with it!

2 comments:

Unknown said...

Really useful content. Thumbs up

Md Ghouse said...

Wow excellent