BHB*_*HBH 59 javascript error-handling node.js
在尝试require()不存在的模块时,我的代码中有一点障碍.代码循环遍历目录并var appname = require('path')在每个文件夹上执行操作.这适用于适当配置的模块,但抛出:Error: Cannot find module当循环命中非模块时.
我希望能够优雅地处理这个错误,而不是让它停止我的整个过程.简而言之,如何捕获错误require()?
谢谢!
BHB*_*HBH 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)
}
Run Code Online (Sandbox Code Playgroud)
adi*_*gar 33
如果给定路径不存在,require()将抛出Error,其code属性设置为'MODULE_NOT_FOUND'.
https://nodejs.org/api/modules.html#modules_file_modules
所以在try catch块中执行require并检查 error.code == 'MODULE_NOT_FOUND'
var m;
try {
m = require(modulePath);
} catch (e) {
if (e.code !== 'MODULE_NOT_FOUND') {
throw e;
}
m = backupModule;
}
Run Code Online (Sandbox Code Playgroud)
使用包装函数:
function requireF(modulePath){ // force require
try {
return require(modulePath);
}
catch (e) {
console.log('requireF(): The file "' + modulePath + '".js could not be loaded.');
return false;
}
}
Run Code Online (Sandbox Code Playgroud)
用法:
requireF('./modules/non-existent-module');
Run Code Online (Sandbox Code Playgroud)
当然基于OP答案
| 归档时间: |
|
| 查看次数: |
38148 次 |
| 最近记录: |