简体   繁体   中英

Unhandled Error in Node JS Application

I have unhandled piece of code in my NodeJS apps data layer that connects to DB. I am explicitly generating error in my code, at the same time not catching it. This is:

AdminRoleData.prototype.getRoleByRoleId = function (params) {
    var connection = new xtrDatabaseConnection();
    var query = "CALL role_getRoleByRoleId(:p_RoleId)";
    var replacements = { p_RoleId: params.roleId };
    replacements = null;
    return connection.executeQuery(query, Sequelize.QueryTypes.RAW, replacements);
} 

replacements = null; this is where i am generating error. No error handling at the moment here. I want to capture these sort of unhandled errors in my application. And want to log them on to file as unhandled exceptions or errors.

process.on('uncaughtException', (err) => {
    logger.log('whoops! There was an uncaught error', err);
    // do a graceful shutdown,
    // close the database connection etc.
    process.exit(1);
});

My question is that my "uncaughtException" is not getting called. Any help ? Or best practices in such scenarios. Or to catch them globally at some centralized place.

simply put the code inside a try-catch block and log them ....

try {
    //your code that might cause an error to occur
}catch (e){
    console.log("ERROR:" + e.toString());
}

If you are using express, you would first define all your routes as:

app.use('/api/users', users); app.use('/api/accounts', accounts); ...

Then you could catch the 404 errors like so:

app.use(function(req, res, next) {
  console.log("A request triggered 404");
  next(err);
});

Finally the block, to catch all errors:

    // error handler
app.use(function(err, req, res, next) {
  console.log(err.message);
  res.status(err.status || 500);
  res.render('error');
});

Note: The order of the functions is important. For example if you put the 404 handler before the other routes then all you responses will be 404. Node will traverse the routes in the order in which you declare them until it finds a match.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM