0
0
NodejsHow-ToBeginner · 3 min read

How to Use Domain Module in Node.js for Error Handling

In Node.js, the domain module helps catch errors across asynchronous operations by creating a domain that handles errors emitted by event emitters or callbacks. You create a domain with domain.create(), run your code inside it, and listen for errors on the domain to prevent crashes.
📐

Syntax

The domain module provides a way to handle multiple I/O operations as a single group for error handling. You create a domain using domain.create(). Then you run your code inside the domain using domain.run(callback) or add event emitters to the domain with domain.add(emitter). You listen for errors on the domain with domain.on('error', handler).

javascript
const domain = require('domain');

const d = domain.create();

d.on('error', (err) => {
  console.error('Domain caught error:', err);
});

d.run(() => {
  // Your async code here
});
💻

Example

This example shows how to catch an error thrown asynchronously inside a domain. The domain catches the error and prevents the Node.js process from crashing.

javascript
const domain = require('domain');

const d = domain.create();

d.on('error', (err) => {
  console.log('Caught error:', err.message);
});

d.run(() => {
  setTimeout(() => {
    throw new Error('Something went wrong!');
  }, 100);
});
Output
Caught error: Something went wrong!
⚠️

Common Pitfalls

One common mistake is not attaching event emitters or asynchronous callbacks to the domain, so errors escape the domain's error handler. Another is relying on the domain module for new projects, as it is deprecated and not recommended for production use. Instead, use modern error handling patterns like async/await with try/catch or error-handling middleware.

javascript
const domain = require('domain');

const d = domain.create();

d.on('error', (err) => {
  console.error('Domain caught error:', err);
});

// Wrong: throwing error outside domain.run
setTimeout(() => {
  throw new Error('This error is not caught by domain');
}, 100);

// Right: throwing error inside domain.run
// d.run(() => {
//   setTimeout(() => {
//     throw new Error('This error is caught by domain');
//   }, 100);
// });
📊

Quick Reference

  • domain.create(): Creates a new domain object.
  • domain.run(callback): Runs code inside the domain context.
  • domain.add(emitter): Adds an event emitter to the domain.
  • domain.on('error', handler): Handles errors emitted in the domain.

Note: The domain module is deprecated and should be avoided in new projects.

Key Takeaways

The domain module groups asynchronous operations to catch errors in one place.
Use domain.run() to execute code inside the domain context for error handling.
Always listen for 'error' events on the domain to handle exceptions.
The domain module is deprecated; prefer modern async error handling methods.
Do not throw errors outside the domain context if you want them caught.