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 Dec 27, 2025

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