处理node.js中require()模块抛出的错误 [英] Handle errors thrown by require() module in node.js
问题描述
在尝试要求()不存在的模块时,我的代码中有一点阻碍。
代码循环遍历一个目录,并在每个文件夹上执行一个 var appname = require('path')
。这适用于适当配置的模块,但抛出:错误:当循环命中非模块时,找不到模块
。
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.
我想要能够妥善地处理这个错误,而不是让它停止我的整个过程。所以简而言之,如何捕获由 require()
抛出的错误?
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()
?
谢谢!
推荐答案
看起来像一个try / catch块这样做的技巧例如
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)
}
这篇关于处理node.js中require()模块抛出的错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!