在 node.js 中加载模块时如何处理错误
假设是这样的:
mysql = require('mysql') ;
当加载 mysql 模块出错时,我想更优雅地处理错误。
像这样的东西:
try:
mysql = require('mysql') ;
catch(e):
console.log("there is a error loading module X");
问题的另一部分是我正在寻找一种基于主机操作系统加载模块的方法。例如,在 linux 上加载一些模块,在 windows 上加载其他模块。
谢谢
最佳答案
这工作得很好:
try {
var mysql = require('mysql');
} catch(e) {
console.log('error loading mysql module', e);
};
根据操作系统加载模块可以通过检查
os.platform()
来完成。 :var platform = require('os').platform();
if (platform === 'linux') {
...
}
else
if (platform === 'windows') { // not sure if its called `windows` because I don't have a Windows machine
...
};
关于node.js - 加载模块时的nodejs异常处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15596729/