node.js - 加载模块时的nodejs异常处理

标签 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 上加载其他模块。
谢谢

最佳答案

这工作得很好:

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/

相关文章:

node.js - Node Js 用户管理

python - 在for循环内尝试/Except行为异常

python - discord.py bot 只响应一个命令

asp.net-mvc - asp.net MVC图像的CustomErrors的最佳方法

ruby-on-rails - Windows 10上的Ruby on Rails错误

php - 如何在 Travis CI 上的 PHP 容器上安装特定的 node.js 版本?

node.js - MongoSkin "Cannot read property ' 未定义的应用'

javascript - 将图像从一个文件夹复制到 digitalocean 空间中的另一个文件夹

node.js - NPM错误: 503 Service Unavailable for npm install command

c# - 将错误传递回调用代码的正确方法