异步等待中的错误处理 [英] Error handling in async await
本文介绍了异步等待中的错误处理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何为Mongoose(当前版本v5.1.5)实施错误处理?
How can you implement error handling for Mongoose (current version v5.1.5)?
例如,让我们假设下面的代码正在查找用户详细信息.
For example, let's assume the following code where a user detail is being looked up.
let u = await user.find({ code: id }).lean();
return u;
发生一些错误,应该如何处理?
And some error occurs, how should it be handled?
第二,我们能否拥有集中的错误处理功能,该功能将在任何Mongoose代码中发生错误时触发,并将其定向到项目中可以处理的特定功能.
Secondly, can we have centralised error handling function which will get triggered whenever an error happens in any of the Mongoose code, it gets directed to a particular function in the project where it can be handled.
推荐答案
在异步等待的.catch
方法中您将得到错误
You will get error in .catch
method of async await
假设您有一个函数
handleErrors(req, res, err) {
return res.json({
success: false,
message: err,
data: null
})
}
这是您的查询
try {
let u = await user.find({ code: id }).lean();
return u;
} catch(err) {
handleErrors(req, res, err) //You will get error here
}
您可以检查这里了解更多
这篇关于异步等待中的错误处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文