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


Question

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!

1
57
11/3/2012 11:48:30 PM

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)
}
51
11/3/2012 11:48:51 PM

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon