codingstuff.io
ExploreTutorialsProblemsCS Subjects
Get Started
ExploreTutorialsProblemsCS Subjects
Get Started
codingstuff.io

Master the art of building software through interactive tutorials, real-world problems, and guided projects.

Pune, Maharashtra, India

codingstuffmail@gmail.com

Product

  • Explore
  • Tutorials
  • Problems
  • CS Subjects

Company

  • About
  • Contact
  • Privacy Policy
  • Terms & Conditions
  • Sitemap

© 2026 codingstuff.io. All rights reserved.

Built with ❤️ for developers everywhere

/
/
All Tutorials
🟢

Node.js

18 / 63 topics
13Child Processes14Clusters15Async Programming16Promises17Async/Await18Error Handling
Tutorials/Node.js/Error Handling
🟢Node.js

Error Handling

Updated 2026-05-15
10 min read

Error Handling

Introduction

In any application, errors are inevitable. They can occur due to various reasons such as invalid user input, network issues, or unexpected server behavior. Proper error handling is crucial for building robust and reliable applications. In Node.js, effective error handling ensures that your application can gracefully handle these situations without crashing.

This tutorial will cover best practices for error handling in Node.js applications. We'll explore different strategies and techniques to manage errors effectively, ensuring a better user experience and easier debugging.

Concept

Error handling in Node.js involves several key concepts:

  1. Try-Catch Blocks: These are used to handle synchronous code.
  2. Callbacks with Error Handling: Commonly used for asynchronous operations.
  3. Promises and Async/Await: Modern approaches for handling asynchronous errors.
  4. Middleware: Used in frameworks like Express.js to centralize error handling.

Try-Catch Blocks

Try-catch blocks are the most basic form of error handling in JavaScript. They allow you to catch exceptions that occur within a try block.

JavaScript
1try {
2// Code that might throw an exception
3} catch (error) {
4// Handle the error
5}

Callbacks with Error Handling

In Node.js, many asynchronous operations use callbacks. The first argument of the callback function is typically reserved for errors.

JavaScript
1function readFile(filePath, callback) {
2fs.readFile(filePath, (err, data) => {
3 if (err) {
4 return callback(err);
5 }
6 callback(null, data);
7});
8}
9
10readFile('example.txt', (err, data) => {
11if (err) {
12 console.error('Error reading file:', err);
13 return;
14}
15console.log(data);
16});

Promises and Async/Await

Promises provide a more elegant way to handle asynchronous operations. They represent the eventual completion (or failure) of an asynchronous operation.

JavaScript
1const fs = require('fs').promises;
2
3async function readFileAsync(filePath) {
4try {
5 const data = await fs.readFile(filePath, 'utf8');
6 console.log(data);
7} catch (error) {
8 console.error('Error reading file:', error);
9}
10}
11
12readFileAsync('example.txt');

Middleware

In frameworks like Express.js, middleware functions can be used to handle errors. Error-handling middleware is defined with four arguments: err, req, res, and next.

JavaScript
1const express = require('express');
2const app = express();
3
4app.get('/', (req, res) => {
5throw new Error('Something went wrong!');
6});
7
8// Error-handling middleware
9app.use((err, req, res, next) => {
10console.error(err.stack);
11res.status(500).send('Something broke!');
12});
13
14app.listen(3000, () => {
15console.log('Server is running on port 3000');
16});

Examples

Let's look at some practical examples to illustrate these concepts.

Example 1: Try-Catch Block

JavaScript
1function divide(a, b) {
2try {
3 if (b === 0) {
4 throw new Error('Division by zero is not allowed');
5 }
6 return a / b;
7} catch (error) {
8 console.error(error.message);
9 return null;
10}
11}
12
13console.log(divide(10, 2)); // Output: 5
14console.log(divide(10, 0)); // Output: Division by zero is not allowed

Example 2: Callback with Error Handling

JavaScript
1const fs = require('fs');
2
3function readFile(filePath, callback) {
4fs.readFile(filePath, 'utf8', (err, data) => {
5 if (err) {
6 return callback(err);
7 }
8 callback(null, data);
9});
10}
11
12readFile('example.txt', (err, data) => {
13if (err) {
14 console.error('Error reading file:', err);
15 return;
16}
17console.log(data);
18});

Example 3: Promises and Async/Await

JavaScript
1const fs = require('fs').promises;
2
3async function readFileAsync(filePath) {
4try {
5 const data = await fs.readFile(filePath, 'utf8');
6 console.log(data);
7} catch (error) {
8 console.error('Error reading file:', error);
9}
10}
11
12readFileAsync('example.txt');

Example 4: Middleware in Express.js

JavaScript
1const express = require('express');
2const app = express();
3
4app.get('/', (req, res) => {
5throw new Error('Something went wrong!');
6});
7
8// Error-handling middleware
9app.use((err, req, res, next) => {
10console.error(err.stack);
11res.status(500).send('Something broke!');
12});
13
14app.listen(3000, () => {
15console.log('Server is running on port 3000');
16});

What's Next?

In the next section, we'll dive into middleware in more detail and explore how it can be used to centralize error handling in Express.js applications.

By following these best practices for error handling, you can build Node.js applications that are more robust and easier to maintain.


PreviousAsync/AwaitNext Middleware

Recommended Gear

Async/AwaitMiddleware