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
}
With this presentation you should always check yourself before accessing data is there any error or not, eg
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)
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;
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.
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.
Top comments (0)