What you need to know about handling errors in Nodejs
Published: 2020-02-29 15:04:25

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](https://dev-to-uploads.s3.amazonaws.com/i/5c0cxeb3wn8leal3g9sv.PNG)

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.
 
2. 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](https://dev-to-uploads.s3.amazonaws.com/i/paheg2zuuc3eagmfcsi7.PNG)

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](https://dev-to-uploads.s3.amazonaws.com/i/liw9zo6ps3zp78a55nwd.PNG)

 
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](https://dev-to-uploads.s3.amazonaws.com/i/6x6jjvkdbnqln2vguebr.PNG)

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

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/dijlb4cpqmx4a4l2ql59.PNG)
 
 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/