Error Handling in Node.js: Types, Examples, and Best Practices

Introduction

Errors are a normal part of application development. A database connection may fail, a file may not exist, an API request may time out, or a user may provide invalid input. If these situations are not handled properly, a Node.js application may return unexpected responses or stop working.

Error handling is the process of detecting errors, managing them safely, and providing meaningful feedback without exposing sensitive application details. Node.js provides several mechanisms for handling errors, including try…catch, error-first callbacks, Promises, and async/await.

Understanding these techniques helps developers build reliable applications, simplify debugging, and prevent unexpected failures.

In this tutorial, you will learn what error handling is in Node.js, explore its syntax and practical examples, understand how to handle errors in Express applications, and review common mistakes and interview questions.

What is Error Handling in Node.js?

Error handling in Node.js is the process of identifying and responding to errors that occur while an application is running.

Errors may occur because of invalid input, unavailable files, database failures, network problems, programming mistakes, or unexpected external service responses.

Node.js supports different error-handling techniques depending on how an operation executes.

Common Types of Errors

  • Syntax errors: Occur when JavaScript code violates language syntax rules.
  • Runtime errors: Occur while the application is running, such as accessing a property on null.
  • Operational errors: Expected failures such as a missing file, a failed network request, or an unavailable database.
  • Logical errors: Occur when the program executes but produces an incorrect result.

Common Error-Handling Techniques

  • try…catch handles synchronous exceptions and errors from awaited Promises inside the try block.
  • Error-first callbacks pass an error as the first argument.
  • Promise .catch() handles rejected Promises.
  • async/await makes asynchronous code easier to read and allows rejected Promises to be handled with try…catch.
  • Express error-handling middleware centralizes errors from HTTP request handlers.

Choosing the correct technique depends on whether the operation is synchronous, callback-based, or Promise-based.

Syntax

1. Using try…catch

The try…catch statement handles exceptions thrown during execution of the try block.


try {
    const result = JSON.parse('{invalid json}');
    console.log(result);
} catch (error) {
    console.error('Error:', error.message);
}

The try block contains the code that may fail. If an exception is thrown, execution moves to the catch block, where the error can be logged or handled.

2. Using Error-First Callbacks

Some Node.js APIs use callbacks where the first argument represents an error.


const fs = require('fs');
fs.readFile('example.txt', 'utf8', (error, data) => {
    if (error) {
        console.error('Unable to read file:', error.message);
        return;
    }
    console.log(data);
});

If the file cannot be read, the callback receives an error. Otherwise, the file content is available in data.

3. Using Promises

A Promise can handle failures through .catch().


Promise.reject(new Error('Operation failed'))
    .then((result) => {
        console.log(result);
    })
    .catch((error) => {
        console.error('Error:', error.message);
    });

The .catch() handler processes a rejected Promise and can also handle exceptions thrown by preceding .then() handlers.

4. Using async/await

With async/await, asynchronous operations can be handled using familiar try…catch syntax.


async function getData() {
    try {
        const response = await fetch(
           'https://jsonplaceholder.typicode.com/posts/1'
        );
        if (!response.ok) {
            throw new Error(`HTTP error: ${response.status}`);
        }
        const data = await response.json();
        console.log(data);
    } catch (error) {
        console.error('Request failed:', error.message);
    }
}
getData();

This example uses the built-in fetch() API available in modern Node.js versions. The response.ok check is important because HTTP error statuses do not automatically reject a Fetch Promise.

Example: Create a Custom Error in Node.js

Developers can create custom errors to represent application-specific failures. For example, an application may need to report when a requested user does not exist.

Create a file named error-example.js:


class AppError extends Error {
    constructor(message, statusCode = 500) {
        super(message);
        this.name = 'AppError';
        this.statusCode = statusCode;
    }
}
function getUser(userId) {
    if (!userId) {
        throw new AppError('User ID is required', 400);
    }

    if (userId !== 1) {
        throw new AppError('User not found', 404);
    }
    return {
        id: 1,
        name: 'Rahul'
    };
}

try {
    const user = getUser(10);
    console.log(user);
} catch (error) {
    if (error instanceof AppError) {
        console.error(
            `Error ${error.statusCode}: ${error.message}`
        );
    } else {
        console.error('Unexpected error:', error);
    }
}

Output

Error 404: User not found

Explanation:

  1. AppError extends JavaScript’s built-in Error class.
  2. The constructor stores a message and an HTTP status code.
  3. getUser() validates the user ID and throws an appropriate error.
  4. The catch block identifies application errors and displays a suitable message.

Custom errors help separate expected application failures from unexpected programming errors. In an HTTP application, the status code can be used to create an appropriate response.

Real-Life Example: Error Handling in an Express API

Consider a REST API that retrieves user information. If the requested user does not exist, the API should return a 404 Not Found response instead of crashing or returning misleading data.

Install Express:


npm install express

Create server.js:


const express = require('express');
const app = express();

app.get('/users/:id', async (req, res, next) => {
    try {
        const userId = Number(req.params.id);

        if (!Number.isInteger(userId) || userId <= 0) {
            const error = new Error('Invalid user ID');
            error.statusCode = 400;
            throw error;
        }

        // Example data; replace with a database query.
        const users = [
            { id: 1, name: 'Rahul' },
            { id: 2, name: 'Priya' }
        ];

        const user = users.find(item => item.id === userId);

        if (!user) {
            const error = new Error('User not found');
            error.statusCode = 404;
            throw error;
        }

        res.json(user);
    } catch (error) {
        next(error);
    }
});

app.use((error, req, res, next) => {
    if (res.headersSent) {
        return next(error);
    }

    const statusCode = error.statusCode || 500;

    if (statusCode >= 500) {
        console.error(error);
    }

    res.status(statusCode).json({
        success: false,
        message: statusCode >= 500
            ? 'Internal server error'
            : error.message
    });
});

app.listen(3000, () => {
    console.log('Server running on port 3000');
});

Test the API

Run the application:


node server.js

Open these URLs in a browser or API client:

  • http://localhost:3000/users/1 — returns the user details.
  • http://localhost:3000/users/10 — returns a 404 Not Found response.
  • http://localhost:3000/users/abc — returns a 400 Bad Request response.

The route passes errors to next(error), and the error-handling middleware creates a consistent JSON response. Unexpected server errors are logged, while clients receive a generic message that does not reveal internal implementation details.

For Express 4, explicitly forwarding errors from asynchronous handlers with next(error) is important. Express 5 automatically forwards rejected Promises returned by route handlers to error-handling middleware, although centralized middleware is still useful.

Common Mistakes in Node.js Error Handling

1. Ignoring rejected Promises

If an asynchronous operation fails and its rejection is not handled, it may result in an unhandled rejection. Use await with try…catch or attach an appropriate rejection handler.

2. Assuming try…catch handles every asynchronous error

A try…catch block does not automatically catch errors thrown later inside an unrelated callback. Handle errors within callbacks or use Promise-based APIs with await.

3. Ignoring callback errors

Always check the error argument in error-first callbacks before using the returned data.

4. Returning incorrect HTTP status codes

Use suitable status codes, such as 400 for invalid input, 404 for missing resources, and 500 for unexpected server failures.

5. Exposing sensitive information

Avoid sending stack traces, database details, file paths, or secrets to clients. Keep detailed diagnostics in secure server logs.

6. Continuing after an unrecoverable error

Do not assume an application can safely continue after an unexpected failure that leaves its state uncertain. Log the error, perform appropriate cleanup, and use a controlled shutdown strategy when necessary.

7. Logging errors without handling them

Logging an error does not necessarily resolve the problem. Decide whether the request can be retried, a safe response can be returned, or the process needs recovery.

Conclusion

Error handling is an essential part of building reliable Node.js applications. It helps developers manage invalid input, failed file operations, rejected Promises, database errors, and unexpected application failures.

Node.js provides several techniques, including try…catch, error-first callbacks, Promises, and async/await. Express applications can also use centralized error-handling middleware to return consistent HTTP responses.

By validating input, handling asynchronous failures, logging useful diagnostics, and avoiding the exposure of sensitive details, developers can build more secure and maintainable Node.js applications.

Error Handling in Node.js – Interview Questions

Q 1: What is error handling in Node.js?
Ans: Error handling is the process of detecting and managing application failures so the application can respond appropriately and avoid unexpected behavior.
Q 2: What is the difference between synchronous and asynchronous errors?
Ans: Synchronous errors occur during the current execution flow, while asynchronous errors may occur in callbacks or Promise-based operations that complete later. Their handling depends on the API being used.
Q 3: What is the purpose of try...catch?
Ans: It catches exceptions thrown within the try block and allows the application to handle them in the catch block.
Q 4: What is an error-first callback?
Ans: It is a callback convention where the first argument contains an error if the operation fails, usually followed by the result.
Q 5: What is custom error handling?
Ans: Custom error handling uses application-defined error classes or properties to represent specific failures and manage them consistently.

Related Node.js Tutorials