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

时间:2017-09-28 09:59:46

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

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

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

replacementments = 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"没有被召唤。有帮助吗?或者在这种情况下的最佳实践。或者在一些集中的地方全球捕捉它们。

2 个答案:

答案 0 :(得分:1)

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

// Defines and manipulates the datepickers
job.dateControl = function() {
    var datepickers = $(".js-datepicker");
    datepickers.each(function () {
        var dateToday = new Date();
        $(this).datepicker({
            defaultDate: "+1w",
            changeMonth: false,
            numberOfMonths: 2,
            dateFormat: "dd/mm/yy",
            beforeShowDay: function (d) {
                var dmy = "";
                if (d.getDate() < 10) dmy += "0";
                dmy += d.getDate();
                dmy += "/";
                if (d.getMonth() < 9) dmy += "0";
                dmy += (d.getMonth() + 1);
                dmy += "/";
                dmy += d.getFullYear();
                console.log(dmy + ' : ' + ($.inArray(dmy, job.unavailableDates)));

                if ($.inArray(dmy, job.unavailableDates) !== -1) {
                    return [false, "", "Unavailable"];
                } else {
                    return [true, "", "Available"];
                }
            },
            minDate: dateToday
        });
        $(this).datepicker("option", "minDate", dateToday);
    });
}

答案 1 :(得分:1)

如果您使用快递,则首先将所有路线定义为:

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。 节点将按照您声明它们的顺序遍历路由,直到找到匹配为止。

相关问题