Handling network errors
So far, we have handled the happy path of dealing with network requests. However, what if things don’t go so smoothly? We still need to build robust and resilient apps, which will react to those special events (or to exceptions).
How to do it…
In this example, we are going to discover sophisticated resiliency patterns and learn how to deal with network errors.
Step 1 – Catching errors
The simplest way to react to network error is just to use the catchError operator from RxJS:
getRecipes$(): Observable<Recipe[]> {
return this.httpClient.get<Recipe[]>(
'https://super-recipes.com/api/recipes'
).pipe(
catchError((error) => {
this._snackBar.open(
'Recipes could not be fetched.',
'Close'
);
return EMPTY;
})
);
}
The strategy here is pretty simple. If there is a request error...