UnhandledPromiseRejectionWarning:API 未处理的承诺拒绝

fai*_*n98 0 javascript json node.js es6-promise

我正在尝试 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")
})
Run Code Online (Sandbox Code Playgroud)

和我的 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})
})
Run Code Online (Sandbox Code Playgroud)

jfr*_*d00 5

你的代码:

axios(...).then(...).catch(error => { throw error;})
Run Code Online (Sandbox Code Playgroud)

axios()如果您的呼叫或.then()处理程序被拒绝,将导致该警告。

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

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


您还应该明白这.catch(error => { throw error;})绝对没有任何用处。它捕获拒绝,然后抛出,这只是再次拒绝链。而且,由于没有其他东西在监听承诺链,所以这是一个未经处理的拒绝。

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

axios(...).then(...).catch(error => {
    console.log(err);
    res.sendStatus(500);
});
Run Code Online (Sandbox Code Playgroud)

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