Skip to content

Instantly share code, notes, and snippets.

@ORESoftware
Created December 16, 2018 21:19
Show Gist options
  • Save ORESoftware/193cdaba7fe1d3b09f703abb132d1ac3 to your computer and use it in GitHub Desktop.
Save ORESoftware/193cdaba7fe1d3b09f703abb132d1ac3 to your computer and use it in GitHub Desktop.
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