Node JS 应用程序中未处理的错误

Unhandled Error in Node JS Application

我的 NodeJS 应用程序数据层中有一段未处理的代码连接到数据库。我在我的代码中明确生成错误,同时没有捕获它。这是:

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

替换 = 空;这是我产生错误的地方。目前这里没有错误处理。我想在我的应用程序中捕获这些未处理的错误。并希望将它们作为未处理的异常或错误记录到文件中。

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

我的问题是我的 "uncaughtException" 没有被调用。有什么帮助吗?或者在这种情况下的最佳实践。或者在某个集中的地方在全球范围内捕获它们。

只需将代码放入 try-catch 块中并记录它们....

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

如果您使用 express,您首先要将所有路线定义为:

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

然后你可以像这样捕获 404 错误:

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

最后是块,捕获所有错误:

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

注意:函数的顺序很重要。例如,如果您将 404 处理程序放在其他路由之前,那么您所有的响应都将是 404。 Node 将按照您声明的顺序遍历路由,直到找到匹配项。