UnhandledPromiseRejectionWarning:API 未处理的承诺拒绝

UnhandledPromiseRejectionWarning: Unhandled promise rejection for 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})
})

您的代码:

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

将导致该警告。

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

您的客户端代码存在完全相同的问题。


您还应该了解 .catch(error => { throw error;}) 绝对没有任何用处。它捕捉到拒绝,然后抛出再次拒绝链。而且,由于没有其他任何东西在监听 promise 链,因此这是一个未处理的拒绝。

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

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

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

我刚开始的时候也是这么做的。 :)

你不会 棒球从 接住 人的手套,所以你不应该从 catch 方法之一。但是,您可以从 then 方法中抛出,它将被以下 catch 方法捕获。

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

.catch(error => yourCustomErrorHandlerThatShouldBeAvailableGloballyAndDefinitelyNotHaveANameThisLong(error))

您的自定义错误处理程序可以为所欲为。你可以将它转发给你用来跟踪崩溃的服务,你可以向页面访问者显示一些东西,你可以将它打印到控制台,让页面快速旋转并爆炸,创建动画猫暴雨,重定向到 Darth维达大喊 "NOOOOOOO!"。天空是极限。

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