Master Node.js From Scratch

Clear, interactive, and structured Node.js lessons designed for beginners and developers.

COURSE SYLLABUS
1. Introduction to Node.js
Introduction to Node.js What Is Node.js? Node.js Architecture Features of Node.js Node.js vs Browser JavaScript Node.js Use Cases
2. Installation and Setup
Installation Introduction LTS and Current Versions npm Setup Environment Setup Verify Installation Node.js REPL
3. Node.js Fundamentals
Fundamentals Introduction Running JavaScript Global Objects Process Object Command-Line Arguments Environment Variables
4. JavaScript Basics
JavaScript Basics Introduction Variables: var, let and const JavaScript Data Types Comparison and Logical Operators If, Else If, Else and Switch Loops and Iteration Functions and Arrow Functions JavaScript Array Methods
5. Node.js Modules
Modules Introduction CommonJS Modules ES Modules Export and Import Built-in Modules Creating Custom Modules Path Module OS Module
6. Working with JSON
JSON Introduction JSON Syntax JSON.stringify() JSON.parse() JSON Array of Objects JSON User Database
7. Node Package Manager
npm Introduction package.json Installing Packages Dependencies and DevDependencies npm Scripts Package Versions and Semantic Versioning npm init and Project Setup
8. File System
File System Introduction Reading Files Writing Files Appending Files Deleting Files Working with Directories
9. CLI Applications
CLI Applications Introduction Command-Line Input Task Manager Project Structure Reading todos.json Adding, Updating and Deleting Tasks Saving Tasks to JSON
10. Events and EventEmitter
Events Introduction EventEmitter Registering Events Emitting Events Removing Event Listeners Custom Events
11. Asynchronous Programming
Async Programming Introduction Callbacks Promises async and await setTimeout() and setInterval() Event Loop and Non-Blocking I/O
12. Native HTTP Module
HTTP Module Introduction Creating an HTTP Server Handling Requests Sending Responses HTTP Request Methods Status Codes and Headers Handling POST Request Body Parsing Incoming JSON Products JSON API
13. Express.js
Express.js Introduction Installing Express Creating an Express Server Request and Response Objects Route Parameters and Query Strings Serving Static Files
14. Express Middleware
Middleware Introduction Built-in Middleware Application-Level Middleware Router-Level Middleware Custom Middleware Error-Handling Middleware
15. REST API Development
REST API Introduction GET Endpoints POST Endpoints PUT and PATCH Endpoints DELETE Endpoints Request Validation and API Responses
16. Database Integration
Database Introduction MySQL Integration MongoDB Integration Database CRUD Operations Database Queries and Filtering Connection Management
17. Authentication and Authorization
Authentication Introduction Password Hashing User Registration User Login JWT Authentication Authorization and Protected Routes
18. Advanced Node.js
Advanced Node.js Introduction Error Handling Debugging Node.js Applications Streams Buffers Performance and Security

Error Handling in Node.js

Error handling is an important part of Node.js development. It helps developers identify errors, handle unexpected situations, prevent application crashes, and return meaningful responses to users. In this tutorial, we will learn different types of errors and how to handle them using practical JavaScript and Express.js examples.

1. What Is Error Handling?

Error handling is the process of detecting, managing, and responding to errors that occur while a program is running.

For example, an application may fail because a file does not exist, a database connection fails, an API request times out, or a user provides invalid input.

Instead of allowing unexpected failures to produce confusing results, we handle errors and return an appropriate response.

JavaScript
try {
    const result = 10 / 0;

    if (!Number.isFinite(result)) {
        throw new Error("The result is not a finite number.");
    }

    console.log(result);
} catch (error) {
    console.log("Error:", error.message);
}

Output

Terminal
Error: The result is not a finite number.

In this example, throw creates an error, and catch handles it. JavaScript normally evaluates 10 / 0 as Infinity, so the example explicitly checks the result and throws an error.

2. Why Is Error Handling Important?

  • Prevents unexpected failures from being handled poorly.
  • Helps developers identify and troubleshoot problems.
  • Provides meaningful error messages to users.
  • Protects sensitive technical details from being exposed.
  • Helps APIs return appropriate HTTP status codes.
  • Improves application reliability and maintainability.
  • Makes debugging and production monitoring easier.
Remember: Error handling does not mean hiding every error. It means handling expected failures safely and recording unexpected failures so developers can investigate them.

3. Types of Errors in Node.js

Error Type Description Example
Syntax Error Occurs when JavaScript syntax is invalid. Missing a closing bracket.
Reference Error Occurs when a variable or identifier cannot be resolved. Accessing an undeclared variable.
Type Error Occurs when an operation is invalid for a value's type. Calling a non-function as a function.
Runtime Error An error that occurs while the program is executing. Reading a missing file.
Operational Error An expected failure caused by an external or application condition. Database unavailable or invalid input.
Programmer Error A defect in the program's logic or implementation. Using an incorrect variable or invalid assumption.

The categories can overlap. For example, a missing file produces a runtime error and may also be an operational error that the application can handle.

4. Handling Errors Using try-catch

The try block contains code that may throw an error. If an error is thrown, JavaScript transfers control to the catch block.

JavaScript
try {
    console.log("Program started");

    throw new Error("Something went wrong");

    console.log("This line will not execute");
} catch (error) {
    console.log("Error caught:", error.message);
}

console.log("Program continues");

Output

Terminal
Program started
Error caught: Something went wrong
Program continues

How It Works

  1. The program enters the try block.
  2. The throw statement creates an error.
  3. The remaining statements in that try block are skipped.
  4. The catch block receives the error.
  5. After the catch block finishes, execution continues.
Important: A synchronous try-catch does not automatically catch errors thrown later by an unrelated asynchronous callback. Asynchronous operations need the appropriate error-handling mechanism.

5. Understanding the JavaScript Error Object

JavaScript errors provide useful information about what went wrong. You can inspect the message and stack trace while debugging.

JavaScript
try {
    throw new Error("Unable to process the request");
} catch (error) {
    console.log("Name:", error.name);
    console.log("Message:", error.message);
    console.log("Stack:", error.stack);
}

Expected Output (Illustrative)

Terminal
Name: Error
Message: Unable to process the request
Stack: Error: Unable to process the request
    at ...

The exact stack trace depends on the file name, line number, and execution environment.

Property Purpose
error.name Identifies the error type.
error.message Describes the error.
error.stack Provides debugging information about the call stack.

6. Creating Custom Errors

Sometimes the standard Error object is not descriptive enough. A custom error class lets you represent application-specific failures.

JavaScript
class ValidationError extends Error {
    constructor(message) {
        super(message);

        this.name = "ValidationError";
    }
}

function registerUser(email) {
    if (!email) {
        throw new ValidationError("Email is required");
    }

    return "User registered successfully";
}

try {
    console.log(registerUser(""));
} catch (error) {
    if (error instanceof ValidationError) {
        console.log("Validation failed:", error.message);
    } else {
        console.log("Unexpected error:", error.message);
    }
}

Output

Terminal
Validation failed: Email is required

Here, ValidationError represents an invalid registration input. The application can handle this differently from an unexpected database or programming error.

7. Error Handling with async/await

Node.js applications frequently use asynchronous operations such as database queries, file access, and API requests. When an awaited Promise rejects, a surrounding try-catch can handle it.

JavaScript
function fetchUser() {
    return new Promise((resolve, reject) => {
        reject(new Error("Unable to fetch user"));
    });
}

async function getUser() {
    try {
        const user = await fetchUser();

        console.log(user);
    } catch (error) {
        console.log("Request failed:", error.message);
    }
}

getUser();

Output

Terminal
Request failed: Unable to fetch user

Explanation

  • fetchUser() returns a Promise.
  • The Promise rejects with an Error object.
  • await makes the rejection throw inside the async function.
  • The catch block handles the rejection.
Remember: The try-catch must surround the awaited operation, or the Promise rejection must be handled using another appropriate mechanism.

8. Error Handling with Promise.catch()

When using Promises directly, the .catch() method handles a rejection that has not already been handled in the chain.

JavaScript
Promise.reject(new Error("Database connection failed"))
    .then((result) => {
        console.log(result);
    })
    .catch((error) => {
        console.log("Error:", error.message);
    });

Output

Terminal
Error: Database connection failed

Use .catch() when working with Promise chains. If you rethrow an error or return another rejected Promise inside .catch(), that failure must also be handled by a later handler or the caller.

9. Error Handling with Callbacks

Many Node.js callback APIs use the error-first callback pattern. The first argument represents an error, and the second represents the successful result.

JavaScript
const fs = require("fs");

fs.readFile("missing.txt", "utf8", (error, data) => {
    if (error) {
        console.log("Unable to read file:", error.code);
        return;
    }

    console.log(data);
});

Possible Output

Terminal
Unable to read file: ENOENT

ENOENT commonly means the requested file or directory does not exist. The exact error code depends on the failure.

Important: A surrounding synchronous try-catch generally cannot catch an error reported later through a callback. Check the callback's error argument instead.

10. Error Handling in Express.js

Express applications commonly use error-handling middleware to handle errors from routes in one central location.

An Express error-handling middleware has four parameters: err, req, res, and next.

JavaScript — app.js
const express = require("express");

const app = express();

app.use(express.json());

app.get("/api/users", (req, res, next) => {
    try {
        throw new Error("Unable to retrieve users");
    } catch (error) {
        next(error);
    }
});

// Error-handling middleware must be registered after routes.
app.use((err, req, res, next) => {
    console.error(err);

    if (res.headersSent) {
        return next(err);
    }

    res.status(500).json({
        message: "An internal server error occurred."
    });
});

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

Test the API

HTTP Request
GET http://localhost:3000/api/users

Expected Response

JSON
{
    "message": "An internal server error occurred."
}

The detailed error is logged on the server, while the client receives a generic response. This prevents internal implementation details from being unnecessarily exposed.

11. Handling Asynchronous Express Errors

Asynchronous route errors must reach Express's error-handling middleware. In Express 5, rejected Promises returned by route handlers are forwarded automatically. In Express 4, asynchronous failures generally need to be forwarded explicitly.

Example for Express 5

JavaScript
app.get("/api/data", async (req, res) => {
    const data = await loadData();

    res.json(data);
});

If loadData() rejects, Express 5 forwards the error to error-handling middleware. This example assumes loadData() is an asynchronous function that returns a Promise.

Compatible Explicit Handling Pattern

JavaScript
app.get("/api/data", async (req, res, next) => {
    try {
        const data = await loadData();

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

The explicit pattern works across Express versions and makes the error forwarding visible in the code.

12. Common HTTP Status Codes for Errors

APIs should use status codes that accurately describe the result of the request.

Status Code Meaning Typical Use
400 Bad Request Invalid input or malformed request.
401 Unauthorized Missing or invalid authentication.
403 Forbidden Authenticated user lacks permission.
404 Not Found Requested resource does not exist.
409 Conflict Request conflicts with current resource state.
500 Internal Server Error Unexpected server-side failure.
503 Service Unavailable Service temporarily cannot handle requests.

13. Error Handling Flow

Execute Program

The application performs an operation.

↓
Error Occurs?

Check whether the operation succeeded.

No Error

Continue processing and return the result.

Error Occurs

Catch or forward the error to a handler.

↓
Handle and Log

Return a safe response and record useful diagnostic details.

14. Error Handling Best Practices

  • Use try-catch for synchronous code that may throw.
  • Handle rejected Promises using await with try-catch or .catch().
  • Check the error argument in error-first callbacks.
  • Use centralized error-handling middleware in Express applications.
  • Return appropriate HTTP status codes.
  • Do not expose stack traces, passwords, tokens, or database credentials to clients.
  • Log useful diagnostic information without logging secrets.
  • Validate user input before performing sensitive operations.
  • Do not silently ignore unexpected errors.
  • Use monitoring and graceful shutdown strategies for production applications.
Production note: An uncaught exception can leave an application in an unreliable state. Log the failure, allow your process manager or orchestration system to restart the process where appropriate, and implement graceful shutdown. Do not assume that catching every error makes continuing execution safe.

Important Points to Remember

  • Error handling detects and manages application failures.
  • try-catch handles synchronous exceptions.
  • async/await works with Promise rejections.
  • .catch() handles rejected Promises.
  • Callback APIs often report errors through the first argument.
  • Custom error classes represent application-specific failures.
  • Express error middleware uses four parameters.
  • Express 5 forwards rejected route-handler Promises automatically.
  • Client responses should not expose internal stack traces.

Summary

Error handling is essential for building reliable Node.js applications. By using try-catch, Promise rejection handlers, error-first callbacks, custom errors, and Express error middleware, developers can handle failures more safely and provide consistent API responses. Proper logging and production monitoring also help identify and resolve problems.