DEV Community

primkatena
primkatena

Posted on

What you need to know about handling errors in Nodejs

In this article, we shall discuss error handling methods in Nodejs. To give a better understanding of handling errors in Node.js, let's refresh our mind on the two common approaches: synchronous and asynchronous methods. In the asynchronous approach, also referred to as blocking, a call to a function waits for a non-JavaScript operation (such as API calls) to complete before passing execution command to the function you just called. For example, when a non-JavaScript operation such as reading a file is currently executing, all JavaScript operations or functions will have to wait for the file system to finish reading a file.

With the asynchronous method (or non-blocking approach), however, a call to a JavaScript function does not have to wait for some heavy-processing tasks like reading from a file to finish executing. Instead, the function continues to execute as the other process is still executing tasks. As could be observed, this approach increases the throughput (the number of units that can be processed within a specific period).

This suggests that the way in which we handle errors in a synchronous method is somewhat different from how asynchronous methods work. In particular, for most synchronous methods, errors are handled using the try and catch method, as shown in the code snippet below.

1.Synchronous error handling method : Try and catch mechanism

Alt Text

However, when dealing with an asynchronous method, we do not use try and catch method to handle errors generated by the asynchronous APIs. Try and catch mechanism will not work in an asynchronous function because the code would have exited the try and catch mechanism by the time callback function will be called. A callback is a function that is passed as a parameter to another function (parent). In simpler words, it tells the parent function to execute whatever instructions it contains when the parent function is done executing its task. More technically, asynchronous methods can either be written using callbacks or promises. But do note that not all callbacks are async. I’ll explain these concepts in a bit.

  1. Callbacks In the code below,I defined a callback function cb, it takes data from fs.read() below and modifies it to suit our response object structure. Let’s look at the fs.read(). In Nodejs, the callback will take an Error object as the first parameter. If an error occurred, it will be returned by the first argument and terminate the program. In this instance, the error message “File does not exist” in the event an error occurs. Otherwise, the error object will be set to null and the method will return successfully.

Alt Text

Error-first callback pattern

Moreover, most asynchronous methods in Node.js use the error-first callback pattern. As the name suggests, a callback function is called whether the operation was successful or unsuccessful. The first parameter of the callback function is the error and it will return null if there is no error and jump to the else statement.
Depending on your programming style you can also start with handling the onSuccess operation and the error at the end. It is important to notice that in both cases, the callback is implemented. See figure below for explanation of this concept.

Alt Text

Status code
To summarize, callbacks are used to handle errors and operations in an asynchronous driven program. In both cases, you get either a success code or error code. There are different status codes used with different meanings you can check out on the internet.

However, most programmers are moving away from callbacks as callbacks are difficult to handle and debug when you have many asynchronous calls in one function. This is simply because for each callback, we have to check for errors. As you can imagine, this process is tedious and programmers can easily forget to check for errors in callbacks, resulting in complexities while debugging code. The other challenge is that the second callback has to wait for the first callback to be executed. It is not executed in parallel although some Node.js library like async helps us to process tasks in parallel and in series. This inconvenience is sometimes referred to as the callback hell.

Overcoming Callback Hell using Promises

In order to avoid challenges presented by using callbacks, promises and async functions were introduced. Promises serve the same purpose of callbacks without presenting the challenges outlined above. Promises simply represent the future result of an asynchronous computation.

The advantage of using promises over callbacks is that promises help to write composable code. A promise takes a single function as a parameter. Fundamentally, there are two (2) parameters in every promisify function: the resolve and reject. The resolve event is called when the operation is successful while reject event is called when there is an error while processing the tasks. Here is an example of a function using promises to handle errors:

Alt Text

Besides promises, async functions could be used to solve the challenges callbacks present. An async function looks like this.

Alt Text

Thank you for making it this far with me. I hope you incorporate promises and async functions in your next Node.js project.

References

https://nodejs.org/en/docs/

Top comments (2)

Collapse
 
peygis profile image
PagesCoffy

Thanks for this enlightening article. I'll surely read more on promises and async functions.

Collapse
 
mohsin708961 profile image
{{7*7}}

Awesome