Categories
JavaScript Answers

How to handle errors thrown by require() module in Node.js?

Spread the love

To handle errors thrown by require() module in Node.js, we use a try-catch block.

For instance, we write

let m;
try {
  m = require(modulePath);
} catch (e) {
  if (e.code !== "MODULE_NOT_FOUND") {
    throw e;
  }
  m = backupModule;
}

to wrap the require call in a try block.

And then we add a catch block that checks the error code.

If it’s not 'MODULE_NOT_FOUND', then we throw the e error.

Otherwise, we set m to backupModule.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *