How to Handle Errors in Node.js ?
Last Updated :
24 Sep, 2024
Node.js is a JavaScript extension used for server-side scripting. Error handling is a mandatory step in application development. A Node.js developer may work with both synchronous and asynchronous functions simultaneously. Handling errors in asynchronous functions is important because their behavior may vary, unlike synchronous functions.
How to Handle Errors in Node?
We have many approaches to handle errors in Node js like try-catch, callback functions, promises, and async-await.
While try-catch blocks are effective for synchronous functions, asynchronous functions can be dealt with callbacks, promises, and async-await. Try-catch is synchronous means that if an asynchronous function throws an error in a synchronous try/catch block, no error throws.
Errors thrown in Node.js applications can be handled in the following ways:
Using try-catch block
The try-catch block can be used to handle errors thrown by a block of code.
JavaScript
function dosomething() {
throw new Error(
'a error is thrown from dosomething');
}
function init() {
try {
dosomething();
}
catch (e) {
console.log(e);
}
console.log(
"After successful error handling");
}
init();
Output:
Error: a error is thrown from dosomething
at dosomething (/home/cg/root/6422736/main.js:4:11)
at init (/home/cg/root/6422736/main.js:9:9)
at Object. (/home/cg/root/6422736/main.js:17:1)
at Module._compile (module.js:570:32)
at Object.Module._extensions..js (module.js:579:10)
at Module.load (module.js:487:32)
at tryModuleLoad (module.js:446:12)
at Function.Module._load (module.js:438:3)
at Module.runMain (module.js:604:10)
at run (bootstrap_node.js:389:7)
After successful error handling
Explanation:
The init() function is called which in turn calls dosomething() function which throws an error object. This error object is caught by the catch block of the init() method. If there is no proper handling of the error the program will terminate. The catch block prints the call stack to show the point where the error occurred.
Using callbacks
A callback is a function called at the completion of a certain task. Callbacks are widely used in Node.js as it prevents any blocking and allows other code to be run in the meantime. The program does not wait for the file reading to complete and proceeds to print "Program Ended" while continuing to read the file. If any error occurs like the file does not exist in the system then the error is printed after "Program Ended", else the content of the file is outputted.
JavaScript
const fs = require("fs");
fs.readFile('foo.txt', function (err, data) {
if (err) {
console.error(err);
}
else {
console.log(data.toString());
}
});
console.log("Program Ended");
Output:
Program Ended
[Error: ENOENT: no such file or directory,
open 'C:\Users\User\Desktop\foo.txt'] {
errno: -4058,
code: 'ENOENT',
syscall: 'open',
path: 'C:\\Users\\User\\Desktop\\foo.txt'
}
Explanation:
In this case, the file does not exist in the system hence the error is thrown.
Using promises and promise callbacks
Promises are an enhancement to Node.js callbacks. When defining the callback, the value which is returned is called a "promise". The key difference between a promise and a callback is the return value. There is no concept of a return value in callbacks. The return value provides more control for defining the callback function. In order to use promises, the promise module must be installed and imported into the application. The .then clause handles the output of the promise. If an error occurs in any .then clause or if any of the promises above are rejects, it is passed to the immediate .catch clause. In case of a promise is rejected, and there is no error handler then the program terminates.
JavaScript
const Promise = require('promise');
const MongoClient = require('mongodb').MongoClient;
const url = 'mongodb://localhost/TestDB';
MongoClient.connect(url)
.then(function (err, db) {
db.collection('Test').updateOne({
"Name": "Joe"
},
{
$set: {
"Name": "Beck"
}
});
})
.catch(error => alert(error.message))
Output:
// In this case we assume the url is wrong
MongoError: failed to connect to server [localhost:27017]
// error message may vary
Using async-await
Async-await is a special syntax to work with promises in a simpler way that is easy to understand. When we use async/await, .then is replaced by await which handles the waiting in the function. The error handling is done by the .catch clause. Async-await can also be wrapped in a try-catch block for error handling. In case no error handler exists the program terminates due to an uncaught error.
JavaScript
async function f() {
let response = await fetch('http://xyzurl');
}
// f() becomes a rejected promise
f().catch(alert);
Output:
// the url is wrong //
TypeError: failed to fetch
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
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
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
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