DEV Community

loading...

Functional programming with Angular. 1. Error Handling

Lonli-Lokli
Updated on ・2 min read

Unhandled exception might lead to failed subscription and user's frustration when button click leads to nothing.

You can read about possible error handling strategies with Rxjs here

From functional point of view there are two kind of failures - expected (network call) and unexpected (divide by zero). First one should never crash your application.

Expected error is an operation which either fail or return data.

Usually data model is represented this way

interface Datum<T> {
  data?: T;
  error?: any
}
Enter fullscreen mode Exit fullscreen mode

With this presentation you should always check yourself before accessing data is there any error or not, eg

naive data and error presentation

Also your data become optional, which might lead to new errors in future. There are other approaches with handling data and error, greatly covered in Russian-speaking presentation (I highly recommend turn subtitles if you dont speak Russian, its really worth it)

I will show another approach in sample weather app, here is how it will look like

First naive implementation - separate properties and ngIfElse for handling different views (stackblitz)

first implementation with error data - html
first implementation with error and data - ts

Now we will use Either type from @sweet-monads\either as it gives a lot of additional methods for Either type, which is actually simple

type Either<Error, Data> = Error | Data;
Enter fullscreen mode Exit fullscreen mode

So in our case we will have abstraction over data and error - container which can contain any of them. To make our life easier, we will use one of the greatest features in angular - directives! Look into new directive, IfRight and IfLeft.

either implementation with error and data - html
either implementation with error and data - ts
(stackblitz)

We were able to get rid of additional properties from typescript but out template is heavier then before. We will adopt it with next steps later, lets focus in next chapter on some details with this Either way.

GitHub logo Lonli-Lokli / functional_angular

Created with StackBlitz ⚡️

Discussion (0)