猫鼬中的错误处理 [英] Error handling in Mongoose
问题描述
我正在使用 Restify 和
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);
});
这篇关于猫鼬中的错误处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!