当发生错误时,从猫鼬回调内部返回express路由



我正在尝试各种处理错误的方法。如果我要添加一个新文档并且我想检查名称是否唯一,我可以输入

router.route('/addSomething').post(async (req,res,next) => {
await Document.findOne(
{name: req.body.name}, // search parameter
(error,doc) = { // callback
if(error) return next(error) // pass system generated error to next() and exit route
else if (doc) return next(new Error("This name already exists")) // pass my own error to next() and exit route
})
// everything from now on shouldn't happen
await Document.save() etc...

我遇到的问题是,路由函数继续,即使一个错误已经返回(我理解这是因为返回语句只从回调函数返回)。

我正在寻找一种优雅的方式来处理mongoose/mongodb错误并在错误点退出函数,而无需到处放置try/catch块。

当你在回调函数中返回next(...)时,你实际上并没有从代码的其余部分返回,只是在该函数中返回。为了解决这个问题,我在你的代码中添加了一个continue()函数来继续传入的HTTP请求。

router.route('/addSomething').post(async (req, res, next) => {
await Document.findOne(
{ name: req.body.name }, // search parameter
(error, doc) => { // callback
if (error) return next(error) // pass system generated error to next() and exit route
else if (doc) return next(new Error("This name already exists")) // pass my own error to next() and exit route
continue(); // Call the continue function if function isn't already returned
}
);
function continue() { // Add a continue function
// Continue your code
await Document.save();
// ...
}
});

考虑使用util.promisify来取消回调:

router.route('/addSomething').post(async (req, res, next) => {
try {
var doc = await util.promisify(Document.findOne)(
{ name: req.body.name } // search parameter
);
} catch(error) {
return next(error); // pass system generated error to next() and exit route
}
if (doc) return next(new Error("This name already exists")); // pass my own error to next() and exit route
// everything from now on shouldn't happen
await Document.save() etc...
});

最新更新