Javascript UnhandledPromiseRejectionWarning:此错误源自在没有 catch 块的异步函数内部抛出

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/53940043/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 05:11:06  来源:igfitidea点击:

UnhandledPromiseRejectionWarning: This error originated either by throwing inside of an async function without a catch block

javascriptnode.jsexpress

提问by anny123

I am getting following error in my Node-Express App

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

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)

UnhandledPromiseRejectionWarning:未处理的承诺拒绝。这个错误要么是因为在没有 catch 块的情况下抛出了异步函数,要么是因为拒绝了一个没有用 .catch() 处理过的承诺。(拒绝编号: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")

and calling it inside my api route like this

并像这样在我的 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)
})

From my end, I think I am handling the error by using catch block.

从我的角度来看,我认为我是通过使用 catch 块来处理错误的。

Question:Can someone explain me why I am getting the error and how can I fix it?

问题:有人可以解释我为什么会收到错误消息,我该如何解决?

采纳答案by Estus Flask

.catch(error => { throw error})is a no-op. It results in unhandled rejection in route handler.

.catch(error => { throw error})是一个空操作。它导致路由处理程序中未经处理的拒绝。

As explained in this answer, Express doesn't support promises, all rejections should be handled manually:

本答案所述,Express 不支持承诺,所有拒绝都应手动处理:

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

回答by Sumer

I suggest removing the below code from getMails

我建议从 getMails 中删除以下代码

 .catch(error => { throw error})

In your main function you should put await and related code in Try block and also add one catch block where you failure code.

在您的主函数中,您应该将 await 和相关代码放在 Try 块中,并在失败代码处添加一个 catch 块。



you function gmaiLHelper.getEmails should return a promise which has reject and resolve in it.

你的函数 gmaiLHelper.getEmails 应该返回一个包含拒绝和解决的承诺。

Now while calling and using await put that in try catch block(remove the .catch) as below.

现在,在调用和使用 await 时,将其放入 try catch 块中(删除 .catch),如下所示。

router.get("/emailfetch", authCheck, async (req, res) => {
  //listing messages in users mailbox 
try{
  let emailFetch = await gmaiLHelper.getEmails(req.user._doc.profile_id , '/messages', req.user.accessToken)
}
catch (error) { 
 // your catch block code goes here
})

回答by tmcnicol

You are catching the error but then you are re throwing it. You should try and handle it more gracefully, otherwise your user is going to see 500, internal server, errors.

您正在捕获错误,但随后又将其重新抛出。您应该尝试更优雅地处理它,否则您的用户将看到 500,内部服务器,错误。

You may want to send back a response telling the user what went wrong as well as logging the error on your server.

您可能想要发回一个响应,告诉用户出了什么问题,并在您的服务器上记录错误。

I am not sure exactly what errors the request might return, you may want to return something like.

我不确定请求可能返回什么错误,您可能想要返回类似的内容。

router.get("/emailfetch", authCheck, async (req, res) => {
  try {
    let emailFetch = await gmaiLHelper.getEmails(req.user._doc.profile_id , '/messages', req.user.accessToken)
      emailFetch = emailFetch.data
      res.send(emailFetch)
   } catch(error) {
      res.status(error.response.status)
      return res.send(error.message);
    })

})

This code will need to be adapted to match the errors that you get from the axios call.

需要修改此代码以匹配您从 axios 调用中获得的错误。

I have also converted the code to use the try and catch syntax since you are already using async.

由于您已经在使用异步,因此我还将代码转换为使用 try 和 catch 语法。