本文介绍了UnhandledPromiseRejectionWarning:此错误是由于在没有catch块的情况下抛出异步函数而产生的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的Node-Express应用程序出现以下错误

I am getting following error in my Node-Express App

至少可以说,我创建了一个类似于以下内容的辅助函数

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})
}

然后导入此辅助函数

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块的情况下抛出异步函数而产生的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-30 04:12