【发布时间】: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