Showing posts with label 8.3.23. Show all posts
Showing posts with label 8.3.23. Show all posts

Thursday, 12 November 2020

Angular timeout and error handling with RxJS

@angular/cli: 8.3.23
Source: GitHub

This is a short article which demonstrates how we can leverage RxJS to effectively set a time-out on long running server requests, and then display a meaningful error message when that happens.

For demonstration purpose, I have made use of Angular in-memory-web-api for REST services (Refer to in-memory-web-api).

I have set up text-box and a button, and I would enter a specific item-id to retrieve the corresponding item. For the in-memory-web-api, I have set a delay of 500ms.



If I now add a timeout of 250ms (timeout imported from rxjs/operators), the next button click to call the web-api would time out. Note that, since the button click is tied to an action stream, any error thrown would effectively complete the observable.



For handling this error, my error-handler method checks for the error instance, and it comes as an instance of TimeoutError (also part of rxjs).





Please note that effective handling really depends on the structure of your REST API.

Now comment out the timeout and try fetching with a blank id. The request is again errored out, and effectively handled in my error-handler method.


Try changing the URL from 'api/items' to 'api/item'. The request errors out with a different error, but handled through the same logic.


Cheers!