How to Handle Errors for Async Code in Node.js ?
Last Updated :
10 Jul, 2024
Handling errors effectively in asynchronous code is crucial for building robust and reliable Node.js applications. As Node.js operates asynchronously by default, understanding how to manage errors in such an environment can save you from unexpected crashes and ensure a smooth user experience. This article will guide you through various techniques and best practices for handling errors in asynchronous code in Node.js.
Why Error Handling in Asynchronous Code is Challenging
In synchronous code, error handling is straightforward using try-catch
blocks. However, asynchronous code, particularly callbacks, promises, and async/await, introduces complexity in error management because operations may be completed at different times and not in the sequential order of execution.
This necessitates different approaches to catch and handling errors properly.
Handle error using callback
A callback function is to perform some operation after the function execution is completed. We can call our callback function after an asynchronous operation is completed. If there is some error we can call the callback function with that error otherwise we can call it with the error as null and the result of the asynchronous operation as the arguments.
Installation Steps
Step 1: Make a folder structure for the project.
mkdir myapp
Step 2:Â Navigate to the project directory
cd myapp
Step 3: Initialize the NodeJs project inside the myapp folder.
npm init -y
Project Structure:
Example: In the code example mentioned below, we have simulated an async operation using setTimeout() method. We perform a divide operation that returns the result of the division after 1 second and if the divisor is zero we pass an error Instance to the callback method. If there is no error, we call the callback function with the error as null and the result of division as the arguments. The error and result are handled inside our callback function.
Node
// app.js
const divide = (a, b, callback) => {
setTimeout(() => {
if (b == 0) {
callback(new Error('Division by zero error'))
} else {
callback(null, a / b)
}
}, 1000)
}
divide(10, 2, (err, res) => {
if (err) {
console.log(err.message)
} else {
console.log(`The result of division = ${res}`)
}
})
divide(5, 0, (err, res) => {
if (err) {
console.log(err.message)
} else {
console.log(`The result of division = ${res}`)
}
})
Step to run the application: You can execute your app.js file using the following command on the command line.
node app.js
Output:Â

Handle Promise rejection
Promise in Node.js is a way to handle asynchronous operations. Where we return a promise from an asynchronous function, it can later be consumed using then() method or async/await to get the final value. When we are using the then() method to consume the promise and we have to handle the promise rejections, then we can a catch() call to then() method call. Promise.catch() is a method that returns a promise and its job is to deal with rejected promise.
Syntax:
// func is an async function
func().then(res => {
// code logic
}).catch(err => {
// promise rejection handling logic
})
Now if we want to handle the Promise rejections using async/await then we can easily do it using a simple try/catch block as shown in the syntax given below.
const hello = async () => {
try {
// func is an async function
const res = await func();
} catch(err) {
// error handling logic
}
}
Example: In the below example, we simulate an asynchronous function with setTimeout() method and perform the divide operation inside an async function that returns a Promise. If the divisor is zero, we reject the promise with an error otherwise we resolve it with the result of division.Â
Node
// app.js
const divide = async (a, b) => {
return new Promise((resolve, reject) => {
setTimeout(() => {
if (b == 0) {
reject(new Error('Division by zero error'));
} else {
resolve(a / b);
}
}, 1000);
});
};
// Consuming the promise using then() method
// and handling the rejected promise using
// catch() method
divide(5, 0)
.then((res) => {
console.log(`The result of division is ${res}`);
})
.catch((err) => {
console.log(err.message);
});
// This function is immedietly invoked after
// its execution. In this case we consume the
// promise returned by divide function() using
// async/await and handle the error using
// try/catch block
(async () => {
try {
const res = await divide(10, 5);
console.log(`The result of division is ${res}`);
} catch (err) {
console.log(err);
}
})();
Step to run the application: You can execute your app.js file using the following command on the command line.
node app.js
Output:Â
Similar Reads
Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
JavaScript Tutorial JavaScript is a programming language used to create dynamic content for websites. It is a lightweight, cross-platform, and single-threaded programming language. It's an interpreted language that executes code line by line, providing more flexibility.JavaScript on Client Side: On the client side, Jav
11 min read
Web Development Web development is the process of creating, building, and maintaining websites and web applications. It involves everything from web design to programming and database management. Web development is generally divided into three core areas: Frontend Development, Backend Development, and Full Stack De
5 min read
Spring Boot Tutorial Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
React Interview Questions and Answers React is an efficient, flexible, and open-source JavaScript library that allows developers to create simple, fast, and scalable web applications. Jordan Walke, a software engineer who was working for Facebook, created React. Developers with a JavaScript background can easily develop web applications
15+ min read
Class Diagram | Unified Modeling Language (UML) A UML class diagram is a visual tool that represents the structure of a system by showing its classes, attributes, methods, and the relationships between them. It helps everyone involved in a projectâlike developers and designersâunderstand how the system is organized and how its components interact
12 min read
JavaScript Interview Questions and Answers JavaScript (JS) is the most popular lightweight, scripting, and interpreted programming language. JavaScript is well-known as a scripting language for web pages, mobile apps, web servers, and many other platforms. Both front-end and back-end developers need to have a strong command of JavaScript, as
15+ min read
Steady State Response In this article, we are going to discuss the steady-state response. We will see what is steady state response in Time domain analysis. We will then discuss some of the standard test signals used in finding the response of a response. We also discuss the first-order response for different signals. We
9 min read
React Tutorial React is a JavaScript Library known for front-end development (or user interface). It is popular due to its component-based architecture, Single Page Applications (SPAs), and Virtual DOM for building web applications that are fast, efficient, and scalable.Applications are built using reusable compon
8 min read
Backpropagation in Neural Network Back Propagation is also known as "Backward Propagation of Errors" is a method used to train neural network . Its goal is to reduce the difference between the modelâs predicted output and the actual output by adjusting the weights and biases in the network.It works iteratively to adjust weights and
9 min read