【问题标题】:Unhandled Error in Node JS ApplicationNode JS 应用程序中未处理的错误
【发布时间】:2018-03-10 00:42:33
【问题描述】:

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

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

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 块可以代替?
  • 控制台是否出现未捕获的异常? replacements = null;如何产生异常?。
  • 我明确将其设为 null 以生成异常。

标签: javascript node.js npm mean-stack winston


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

    如果您使用 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 将按照您声明它们的顺序遍历这些路由,直到找到匹配项。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-03-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-12
      • 2020-12-11
      • 2012-05-24
      • 2014-06-28
      相关资源
      最近更新 更多