如何从 mongoose 查询中捕获错误。在我的 route ,我得到了这样的东西:
// router.js
router.route('/signup')
.post(function(req, res) {
var profile = new Profile(); // create a new instance of the profile model
profile.username = req.body.username;
profile.password = profile.generateHash(req.body.password);
profile.save(function(err) {
if (err) { // (A)
throw new Error('user/create error'));
} else {
res.json(200, { user_token: profile._id, username: profile.username });
}
});
});
在我的应用程序中我设置了我的路线我得到了这个:
// app.js
var router = require('./app/routes/routes');
// global-error handling middleware
app.use(function(err, req, res, next) {
console.log('Some error is happening.');
res.json(500, {status: 500, message: err.message});
});
如果我生成错误,那么我会在上面的代码中转到行//(A),我会得到一个堆栈跟踪并且 node.js 存在。我想在我的错误处理程序中捕获错误。我该怎么做?
最佳答案
好吧,您已经在请求处理程序中,并且您已经可以访问保存配置文件对象时产生的错误。所以,这里没有必要抛出异常。您已经可以处理这个问题。
这里最有可能的情况是向用户发送一个响应,指示保存配置文件失败。
function(req, res) {
profile.save(function(err) {
if (err) { // (A)
res.send(500, {message: 'Failed to save profile'}
} else {
res.json(200, { user_token: profile._id, username: profile.username });
}
});
}
就是这样。您的客户端将收到 500 状态错误,这显然表示您的客户端需要处理的问题,例如通知用户、重试等。
关于javascript - 在 express 中捕获来自 mongoose 查询的错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24059258/