未处理的承诺拒绝警告:API 的未处理承诺拒绝



我正在尝试控制台.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;})绝对没有任何用处。 它捕获拒绝,然后抛出,只是再次拒绝链。 而且,由于没有其他东西在监听承诺链,所以这是一个未经处理的拒绝。

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

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

当我开始时,我做了同样的事情。 :)

你不会从球手的手套中扔棒球,所以你也不应该从catch方法出错误。但是,您可以从then方法中抛出,它将被以下catch方法捕获。

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

.catch(error => yourCustomErrorHandlerThatShouldBeAvailableGloballyAndDefinitelyNotHaveANameThisLong(error))

自定义错误处理程序可以执行任何操作。你可以把它转发到你用来跟踪崩溃的服务,你可以向页面访问者显示一些东西,你可以把它打印到控制台,让页面旋转得非常快并爆炸,创建一个动画猫暴雨,重定向到达斯维达大喊"NOOOOOOO!"。天空是极限。

最新更新