UnhandledPromiseRejectionWarning:此错误源于在没有 catch 块的异步函数内部抛出 [英] UnhandledPromiseRejectionWarning: This error originated either by throwing inside of an async function without a catch block
问题描述
我的 Node-Express 应用程序出现以下错误
I am getting following error in my Node-Express App
UnhandledPromiseRejectionWarning:未处理的承诺拒绝.这个错误源于抛出异步函数内部没有 catch 块,或者通过拒绝未处理的承诺与.catch().(拒绝编号:4)
UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 4)
至少可以说,我创建了一个看起来像这样的辅助函数
To say the least, I have created a helper function which looks something like this
const getEmails = (userID, targettedEndpoint, headerAccessToken) => {
return axios.get(base_url + userID + targettedEndpoint, { headers: {"Authorization" : `Bearer ${headerAccessToken}`} })
.catch(error => { throw error})
}
然后我导入这个辅助函数
and then I am importing this helper function
const gmaiLHelper = require("./../helper/gmail_helper")
并像这样在我的 api 路由中调用它
and calling it inside my api route like this
router.get("/emailfetch", authCheck, async (req, res) => {
//listing messages in users mailbox
let emailFetch = await gmaiLHelper.getEmails(req.user._doc.profile_id , '/messages', req.user.accessToken)
.catch(error => { throw error})
emailFetch = emailFetch.data
res.send(emailFetch)
})
从我的角度来看,我认为我是通过使用 catch 块来处理错误的.
From my end, I think I am handling the error by using catch block.
问题:谁能解释一下为什么我会收到错误消息,我该如何解决?
Question: Can someone explain me why I am getting the error and how can I fix it?
推荐答案
.catch(error => { throw error})
是一个空操作.这会导致路由处理程序中未经处理的拒绝.
.catch(error => { throw error})
is a no-op. It results in unhandled rejection in route handler.
如此答案所述,Express 不支持 promise,所有拒绝都应手动处理:
As explained in this answer, Express doesn't support promises, all rejections should be handled manually:
router.get("/emailfetch", authCheck, async (req, res, next) => {
try {
//listing messages in users mailbox
let emailFetch = await gmaiLHelper.getEmails(req.user._doc.profile_id , '/messages', req.user.accessToken)
emailFetch = emailFetch.data
res.send(emailFetch)
} catch (err) {
next(err);
}
})
这篇关于UnhandledPromiseRejectionWarning:此错误源于在没有 catch 块的异步函数内部抛出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!