Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handle errors thrown by require() module in node.js

having a bit of a snag in my code when trying to require() modules that don't exists. The code loops through a directory and does a var appname = require('path') on each folder. This works for appropriately configured modules but throws: Error: Cannot find module when the loop hits a non-module.

I want to be able to handle this error gracefully, instead of letting it stop my entire process. So in short, how does one catch an error thrown by require()?

thanks!

like image 904
bhurlow Avatar asked Nov 02 '12 15:11

bhurlow


People also ask

For what require () is used in NodeJS?

1) require() In NodeJS, require() is a built-in function to include external modules that exist in separate files. require() statement basically reads a JavaScript file, executes it, and then proceeds to return the export object.

How do I fix a Node module error?

If the error is not resolved, try to delete your node_modules and package-lock. json (not package. json ) files, re-run npm install and restart your IDE. Copied!

How would you handle errors for async code in NodeJS?

If we want to handle the error for asynchronous code in Node. js then we can do it in the following two manners. Handle error using callback: A callback function is to perform some operation after the function execution is completed. We can call our callback function after an asynchronous operation is completed.


3 Answers

looks like a try/catch block does the trick on this e.g.

try {
 // a path we KNOW is totally bogus and not a module
 require('./apps/npm-debug.log/app.js')
}
catch (e) {
 console.log('oh no big error')
 console.log(e)
}
like image 153
bhurlow Avatar answered Oct 08 '22 04:10

bhurlow


If the given path does not exist, require() will throw an Error with its code property set to 'MODULE_NOT_FOUND'.

https://nodejs.org/api/modules.html#modules_file_modules

So do a require in a try catch block and check for error.code == 'MODULE_NOT_FOUND'

var m;
try {
    m = require(modulePath);
} catch (e) {
    if (e.code !== 'MODULE_NOT_FOUND') {
        throw e;
    }
    m = backupModule;
}
like image 21
adiktofsugar Avatar answered Oct 08 '22 04:10

adiktofsugar


Use a wrapper function:

function requireF(modulePath){ // force require
    try {
     return require(modulePath);
    }
    catch (e) {
     console.log('requireF(): The file "' + modulePath + '".js could not be loaded.');
     return false;
    }
}

Usage:

requireF('./modules/non-existent-module');

Based on OP answer of course

like image 15
DaniGuardiola Avatar answered Oct 08 '22 02:10

DaniGuardiola