我的 Node-Express 应用程序出现以下错误
UnhandledPromiseRejectionWarning:未处理的承诺拒绝。这个
错误源于在异步函数内部抛出
没有 catch 块,或拒绝未处理的承诺
使用 .catch()。 (拒绝编号:4)
至少可以说,我创建了一个看起来像这样的辅助函数
const getEmails = (userID, targettedEndpoint, headerAccessToken) => {
return axios.get(base_url + userID + targettedEndpoint, { headers: {"Authorization" : `Bearer ${headerAccessToken}`} })
.catch(error => { throw error})
}
然后我正在导入这个辅助函数
const gmaiLHelper = require("./../helper/gmail_helper")
并像这样在我的api路由中调用它
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 块来处理错误。
问题: 谁能解释我为什么会收到错误以及如何解决?
原文由 anny123 发布,翻译遵循 CC BY-SA 4.0 许可协议
.catch(error => { throw error})
是无操作的。它导致路由处理程序中未处理的拒绝。正如 这个答案 中所解释的,Express 不支持承诺,所有拒绝都应该手动处理: