Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Simple use cases for Node.js domain module

First run this code:

const exec = () => {
   setTimeout(() => {
      throw 'nothing can catch this, except domains';
   },10);
};


try{
  exec();
}
catch(err){
  console.error('Error was trapped by try/catch:', err);
}

You will notice that try/catch cannot trap the error. However if we use Node.js domains:

const Domain = require('domain');
const d = Domain.create();

d.once('error', err => {
  console.error('Error was trapped by the domain:', err);
});

d.run(exec);

Domains are useful for trapping errors thrown asynchronously. Using the global uncaughtException and unhandledRejection handlers don't solve the problem either. Only Domains can catch arbitrary errors like this.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.