How To Handle Errors in Asynchronous Javascript Code (when working with Callbacks)

We will use a simple function called calculateSquare to demonstrate how to handle errors in asynchronous Javascript code.

In order to simulate an asynchronous function, we will use setTimeout:

Run the code above and everything works.

But what happens when this function gets a String instead of a Number type? We would get NaN (not a number) for the result. This needs to be handled.

Uncaught Error.

If we run the above code, we will get an Uncaught Error instead of a Caught error from our catch block.

That’s because by the time the Caught error message (from the catch block) has been called, the surrounding code has already been executed before it.

setTimeout will place our callback function in Javascript’s message queue while the try-catch block and other surrounding code resides in the call stack. Everything from the call stack will be executed before we even get to the first item of the message queue. (Read more about the event loop here).

Photo from: dev.to

Traditionally for such cases, errors are handled as arguments of the callback.
The first argument of the callback is usually named error, whereby if something goes wrong in the asynchronous function, then the callback gets called with the first argument which specifies what error has happened.
If everything goes well, then the first argument will be null.
This is called error-first callback, which is a common pattern used in Javascript, especially in NodeJS.

Modified as such:

Now our error goes into the “Caught error” defined by us, rather than being thrown the “Uncaught error”.

Hope this clarifies and helps someone! Cheers.

Credits and code example: Viktor Pyskunov

Software Developer at @thoughtworks | Marathon Runner | Ex-Pharmacist Writing on Coding, Technology and Running

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store