Separation of concerns and error handling in Angular

In Object-Oriented Programming there’s a concept called Single responsability principle which in short says that every module is responsible for only one thing. In Angular this means that components sole responsibility is presentation logic while services are only responsible for getting data.
It happens to see (or write) components like this:
This is really bad.
This component is responsible for too many things:
- Sends HTTP POST to /api/authentication;
- Inserts token into localStorage;
- Navigates client to the home-page;
- Deals with network error and unsuccessful response.
It’s like telling a chef to also serve at tables in a restaurant. Serving meals is not a chef’s responsibility.
Refactoring
We can refactor the code and improve it by A LOT simply by making a service and delegating to it everything it has to do with HTTP.
Let’s make a service:
Now, let’s see how the component looks like:
It feels much better than before!
Yet the way in which the error is handled is sub-optimal.
Expected error handling
Despite the fact the code improved A LOT, there’s room for improvements.
To make things perfect let’s create few custom classes for dealing with errors in our component.
Let’s use those classes within our service:
Now, within our component we can use instanceof operator to check the kind of error we get from our service, look:
Unexpected error handler
Finally we can handle all the remaining errors with a global error handler.
To do so make a class which implements ErrorHandler from @angular/core:
Now, in your module, within the providers array, add:
providers: [
{ provide: ErrorHandler, useClass: AppErrorHandler }
]
The End
We successfully decoupled presentation and data logic.
All expected errors has been handled, and also unexpected ones.
Thanks for reading… Hope it was useful! Bye.