user1229351
user1229351

Reputation: 2035

nodejs exception handling when loading modules

how can i have a error handeling when i load a module in node.js assume something like this:

mysql = require('mysql') ;

i want to handle errors more gracefully when there is a error loading mysql module. something like this:

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

another part of question is im looking for a way to load modules based on the Host operating system. for example load some modules on linux and others on windows. thanks

Upvotes: 0

Views: 358

Answers (2)

robertklep
robertklep

Reputation: 203409

This works just fine:

try {
  var mysql = require('mysql');
} catch(e) {
  console.log('error loading mysql module', e);
};

Loading modules based on OS can be done with checking 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
  ...
};

Upvotes: 2

throrin19
throrin19

Reputation: 18207

Used you express? If yes, you can try the error 500 handling :

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

Upvotes: 0

Related Questions