Error Handling in Node.js

Applications running in Node.js encounter different categories of errors: standard JavaScript errors, DOMExceptions, system errors, assertion errors, and user-defined errors. Node.js provides multiple mechanisms for propagating and handling these errors depending on whether the API is synchronous, asynchronous with callbacks, or asynchronous with Promises. Understanding these mechanisms is essential for building resilient applications.

Standard JavaScript ErrorsSystem ErrorsAssertionErrorError propagationEventEmitter error events

~2 min read · Updated Nov 2, 2026

1. Categories of Errors


  • Standard JavaScript Errors: SyntaxError, ReferenceError, TypeError, etc.
  • DOMExceptions: Standard browser exceptions.
  • System Errors: Triggered by OS constraints (e.g., opening a non-existent file).
  • AssertionError: Raised by the assert module when logic violations occur.
  • User-defined Errors: Errors explicitly thrown in application code.

2. Error Propagation and Handling


Error handling depends on the API style:


  • Synchronous APIs: Use throw and must be handled with try...catch.
  • Promise-based APIs: Errors are reported via reject and handled with catch.
  • Callback-based APIs: Errors are passed as the first argument to the callback.
  • EventEmitter APIs: Errors are emitted via the 'error' event.

3. Examples


// Synchronous
try {
  const m = 1;
  const n = m + z; // ReferenceError
} catch (err) {
  console.error(err);
}

// Asynchronous with Promise
const fs = require('node:fs/promises');
(async () => {
  try {
    await fs.readFile('file.txt');
  } catch (err) {
    console.error('Error reading file!', err);
  }
})();

// Asynchronous with Callback
const fs = require('node:fs');
fs.readFile('file.txt', (err, data) => {
  if (err) {
    console.error('Error reading file!', err);
    return;
  }
});

4. Error Class Properties


  • error.message: Text description of the error.
  • error.code: Stable identifier for the error type.
  • error.stack: Stack trace showing where the error was created.
  • error.cause: Underlying cause of the error (since v16.9.0).

5. Important Error Types


  • AssertionError: Indicates assertion failure.
  • RangeError: Argument outside valid range.
  • ReferenceError: Accessing an undefined variable.
  • SyntaxError: Invalid JavaScript code.
  • SystemError: Errors caused by OS-level constraints.

Conclusion


Proper error handling in Node.js is critical for building stable applications. Developers must understand the different error categories and propagation mechanisms, and use tools like try...catch, Promise.catch, and 'error' events in EventEmitters to handle errors effectively.


Written & researched by Dr. Shahin Siami

Related Articles

Comprehensive Guide to the Node.js VM Module (node:vm)

The node:vm module allows you to compile and execute JavaScript code inside isolated V8 contexts — essentially creating lightweight sandboxes within your Node.js application. These contexts have their own global scope and can run code independently from the main environment. However, vm is NOT a security sandbox. It is powerful for dynamic code execution, template engines, REPLs, plugin systems, and controlled module execution, but it must never be used to run untrusted code.

Continue

Comprehensive Guide to the V8 Module in Node.js (node:v8)

The node:v8 module exposes low-level APIs that interact directly with the V8 JavaScript engine embedded in Node.js. . These APIs provide access to heap statistics, heap snapshots, coverage tools, serialization mechanisms, V8 flags, object queries, and promise lifecycle hooks. The module is essential for performance analysis, memory debugging, tooling, and advanced Node.js internals work.

Continue

Comprehensive Guide to Node.js Worker Threads (node:worker_threads)

The node:worker_threads module enables true multithreading in Node.js by running JavaScript in separate threads. While Node.js is traditionally single‑threaded, worker threads allow CPU‑intensive tasks to run in parallel without blocking the event loop. They support shared memory, zero‑copy transfers, worker pools, resource limits, and advanced synchronization APIs. Worker threads are ideal for heavy computation, data processing, and parallel workloads—while async I/O remains best handled by the main thread.

Continue

Comprehensive Guide to the Node.js util Module (node:util)

The node:util module provides a powerful collection of helper functions used throughout Node.js core and extremely useful for application developers. These utilities support debugging, inspection, formatting, type checking, callback/Promise conversions, argument parsing, text encoding, MIME handling, and more. It is one of the most versatile and essential toolkits in the Node.js ecosystem.

Continue

Comprehensive Guide to the URL Module in Node.js

The node:url module provides tools for parsing, constructing, and manipulating URLs. Node.js supports two URL APIs: WHATWG URL API — modern, browser‑compatible, standards‑based. Legacy Node.js URL API — older, Node‑specific, now discouraged. The WHATWG API is the recommended approach for all modern applications. It provides a clean, consistent interface for working with URL components, query parameters, and structured URL patterns.

Continue

Comprehensive Guide to UDP/Datagram Sockets in Node.js

The node:dgram module provides a full implementation of UDP (User Datagram Protocol) sockets in Node.js. . UDP is a lightweight, connectionless protocol ideal for real‑time applications such as VoIP, gaming, telemetry, IoT, and multicast/broadcast systems. This module exposes APIs for creating sockets, sending and receiving datagrams, joining multicast groups, managing buffer sizes, and controlling low‑level socket behavior.

Continue