Mongoose 中的错误处理 [英] Error handling in Mongoose
问题描述
我正在使用 Restify 和 Mongoose,我对两者都是全新的.我似乎无法找出处理 Mongoose/Node.js 中错误的正确方法.
I'm creating an API using Restify and Mongoose, and I'm completely new to both. I can't seem to figure out the proper way to handle errors in Mongoose / Node.
截至目前,我正在尝试做这样的事情:
As of now, I'm trying to do something like this:
Submission.findById(req.params.submission_id, function(err, data) {
if (err)
return next(err);
res.send(data);
});
我正在尝试对此调用 GET(对于不存在的用户).而不是发回简单的错误消息,它会导致我的整个节点应用程序失败.我对 return next(err) 的用户以及它到底应该做什么感到有些困惑.
I'm attempting to call a GET on this (for a user that not exist). And rather than sending back a simple error message, it causes my entire node application to fail. I'm a bit confused on the user of return next(err) and what that exactly should do.
非常感谢任何帮助.
推荐答案
未找到匹配项的 findById
查询不是 Mongoose 级别的错误,因此您可以根据需要那样对待你必须自己做:
A findById
query that doesn't find a match isn't an error at the Mongoose level, so you if you want it treated that way you have to do it yourself:
Submission.findById(req.params.submission_id, function(err, data) {
if (err)
return next(err);
else if (!data)
return next(new Error("User not found"));
res.send(data);
});
这篇关于Mongoose 中的错误处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!