Error handling in Observable, Promise and Async/await.

HTTP request in JavaScript

Yurii K
Nerd For Tech

--

Every project has to make an HTTP request and of course, some of those requests could have errors. We need to know how to handle those errors.

Because we are talking about HTTP requests I need to mention Observable.

The standard approach is to make a callback function for errors.

Another way is to make a pipe and use catchError from the RxJS library. At this point, we can catch and handle an error in catchError or throw a new error with our description.

Try/catch is working with a modern approach — async/await. We just make a call inside of the try block. If something goes wrong in the catch block we will handle an error, no callbacks here.

Async/await is working with Promise. In Promise, we also can use a callback function to handle errors.

We can combine callback functions with modern async/await. To get the best from two worlds. Inside of the HTTP method we are adding callback functions to handle successful responses and responses with errors. Those handles should return the same object with data or error. With those improvements, we can use async/await.

Now you can find the best solution that fills your needs.

If you need to take a close look at the project here is the link.

Originally published at http://tomorrowmeannever.wordpress.com on April 4, 2022.

--

--

Yurii K
Nerd For Tech

Full-stack developer. In my work, I use Angular and C#. In my free time I write articles for my blog.