在尝试使用不存在的require()模块时,我的代码中有一点小问题。代码循环遍历一个目录,并在每个文件夹上执行var appname = require('path')。这对适当配置的模块有效,但当循环遇到非模块时抛出:Error: Cannot find module。
我希望能够优雅地处理这个错误,而不是让它停止我的整个过程。因此,简而言之,如何捕捉require()抛出的错误
谢谢!
发布于 2012-11-04 07:48:52
看起来try/catch块在这方面做得很好,例如
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)
}发布于 2016-08-11 08:04:27
如果给定的路径不存在,则require()将抛出错误,并将其代码属性设置为“MODULE_ not _FOUND”。
https://nodejs.org/api/modules.html#modules_file_modules
因此在try catch块中执行一个请求并检查error.code == 'MODULE_NOT_FOUND'
var m;
try {
m = require(modulePath);
} catch (e) {
if (e.code !== 'MODULE_NOT_FOUND') {
throw e;
}
m = backupModule;
}发布于 2015-12-01 02:02:19
使用包装器函数:
function requireF(modulePath){ // force require
try {
return require(modulePath);
}
catch (e) {
console.log('requireF(): The file "' + modulePath + '".js could not be loaded.');
return false;
}
}用法:
requireF('./modules/non-existent-module');当然是基于OP答案
https://stackoverflow.com/questions/13197795
复制相似问题