Separation of concerns and error handling in Angular

Fredo Corleone
2 min readMar 28, 2019

Photo by Nathan Dumlao on Unsplash

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.

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

Fredo Corleone
Fredo Corleone

Written by Fredo Corleone

Ex web-app developer. Now just a free man!

No responses yet

Write a response