UnhandledPromiseRejectionWarning:API的未处理的承诺拒绝

我正在尝试用console.log记录天气API的一些数据,但是当我去查找位置时会收到错误消息

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)

到目前为止,我的代码在我的服务器上

app.post('/weather',(req,res) => {
    const url = `https://api.darksky.net/forecast/${DARKSKY_API_KEY}/${req.body.latitude},${req.body.longitude}?units=auto`
    axios({
      url: url,responseType: 'json'
    }).then(data => res.json(data.data.currently)).catch(error => { throw error})
  })

app.listen(3000,() => {
    console.log("Server has started")
})

和我的Javascript

  fetch('/weather',{
    method: 'POST',headers: {
      'Content-Type': 'application/json','accept': 'application/json'
    },body: JSON.stringify({
      latitude: latitude,longitude: longitude
    })
  }).then(res => res.json()).then(data => {
    console.log(data)
    setWeatherData(data,place.formatted_address)
  }).catch(error => { throw error})
})
lwr82545744 回答:UnhandledPromiseRejectionWarning:API的未处理的承诺拒绝

您的代码:

axios(...).then(...).catch(error => { throw error;})
如果您的axios()调用或.then()处理程序被拒绝,则

将导致该警告。

当您在.catch()处理程序中抛出错误时,使承诺链处于拒绝状态,并且您没有其他代码可以捕获该拒绝。

您的客户端代码完全相同。


您还应该了解.catch(error => { throw error;})绝对没有任何用处。它捕获拒绝,然后抛出,仅再次拒绝链。而且,由于没有其他人在听诺言链,这是未处理的拒绝。

您需要做的是以某种适合您的应用程序的方式实际处理错误,例如将错误状态发送回客户端。

axios(...).then(...).catch(error => {
    console.log(err);
    res.sendStatus(500);
});

并且,在客户端中,您可以向用户显示错误消息,也可以仅记录错误。如果没有人听,则重新抛出该错误对您没有好处。

,
axios({
      url: url,responseType: 'json'
    }).then(data => res.json(data.data.currently)).catch(error => { console.error(error)})
,

我刚开始做同样的事情。 :)

您也不会从抓住 er的手套中投掷棒球,因此您也不应该从catch方法中抛出错误。但是,您可以从then方法中抛出,它将被以下catch方法捕获。

无论如何,您应该处理catch方法中的错误。在大多数情况下,如果是真正的错误,错误将自动发送到该catch方法。如果是在成功的API请求中隐藏的错误,则必须像我上面提到的那样手动引发错误。

.catch(error => yourCustomErrorHandlerThatShouldBeAvailableGloballyAndDefinitelyNotHaveANameThisLong(error))

您的自定义错误处理程序可以执行您想要的任何操作。您可以将其转发到用于跟踪崩溃的服务,可以向页面访问者显示内容,可以将其打印到控制台,使页面真正快速旋转并爆炸,创建动画猫暴雨,重定向到Darth维达大喊“ NOOOOOOO!”。天空是极限。

本文链接:https://www.f2er.com/2807224.html

大家都在问