加载模块时的nodejs异常处理

时间:2013-03-24 09:05:04

标签: node.js error-handling

当我在node.js中加载模块时,如何处理错误 假设这样的事情:

mysql = require('mysql') ;

我想在加载mysql模块时出错,更优雅地处理错误。 像这样的东西:

try: 
mysql = require('mysql') ;
catch(e):
console.log("there is a error loading module X");

问题的另一部分是我正在寻找一种基于主机操作系统加载模块的方法。例如,在Linux上加载一些模块,在Windows上加载其他模块。 感谢

2 个答案:

答案 0 :(得分:2)

这很好用:

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
  ...
};

答案 1 :(得分:0)

你用过快递吗?如果是,您可以尝试错误500处理:

app.use(function(err, req, res, next){
    console.log("this is an error");
});