【问题标题】:How to do error handling in Express and NodeJS for Mongoose Error.如何在 Express 和 NodeJS 中针对 Mongoose 错误进行错误处理。
【发布时间】:2016-08-18 11:53:55
【问题描述】:

我有一个 NodeJS 应用程序,Express 作为我的 Web 服务器,Mongoose 作为我在 MongoDB 上的抽象层。现在一个简单的 Express 路由是这样编写的。

module.exports.getProfile = function(req, res, next) {
    Users.findOne({
        '_id': req.user._id
    }).exec(function(err, profile) {
        if (err) {
            res.sendStatus(500);
        } else if (profile) {
            res.status(200).send(JSON.stringify({
                'profile': profile
            }));
        } else {
            res.status(400).send(JSON.stringify({
                'message': "Profile Not found"
            }));
        }
    });
};

现在我的应用程序中至少有 100 个这样的函数,而不是每次都编写 res.sendStatus(500),我想创建一个这样的函数。

var sendError = function(err, res, next) {
    if (err) {
        res.status(500).send(JSON.stringify({
            'message': "Internal server error. Couldn't connect to database. Please report this issue and try again"
        }));
        next();
    }
};

对于每个数据库调用。 if(err) sendError(err, res, next);不起作用,不知何故我觉得它不对。那么在这种情况下,最佳做法是什么?

【问题讨论】:

    标签: node.js express error-handling mongoose


    【解决方案1】:

    您可以为此目的使用Express.errorHandler。它在Express documentation 中描述。

    【讨论】:

    • Express.errorHandler 是一个快速函数,因为您在上面提供的文档页面的链接中没有给出它。
    • 这是关于 Express 中错误处理工作流程的文档。具有 4 个参数的函数调用错误处理程序,如果您在路由中调用 next() 并将 err 传递给它,则将为该函数提供执行流程。
    • 好吧,你的意思是说如果我给 next(err);在上述函数中,而不是 res.sendStatus(500);并写一个函数app.use(function(err, req, res, next){ res.status(500).send('Something broke!');}) 会起作用吗?
    • 是的。此外,您必须确保在添加路由功能后添加错误处理程序,如下所示:pastebin
    猜你喜欢
    • 2021-02-19
    • 1970-01-01
    • 2022-06-20
    • 2015-02-15
    • 2021-03-17
    • 1970-01-01
    • 2023-01-05
    • 1970-01-01
    • 2021-08-29
    相关资源
    最近更新 更多