首页 > 解决方案 > UnhandledPromiseRejectionWarning,但我正在处理错误?

问题描述

我收到以下错误:

Houston we got an err at getGames in index.js
(node:72197) UnhandledPromiseRejectionWarning: #<Object>
(node:72197) 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: 2)
(node:72197) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
error at getGames rp

以下是相关代码:

从 API 获取数据的辅助函数(rp 是 request-promise-native)

const getGames = async () => {
   return await rp(`https://api.steampowered.com/IDOTA2Match_570/GetTopLiveGame/v1?key=${KEY}&partner=0`)
   .catch(err => console.log('error at getGames rp'))
   .error(err => console.log('actual error at getGames rp'))
}

我每 5 秒调用一次

app.get('/api/update', async (req, res) => {
  const data = await getGames()
  .catch(err => console.log('Houston we got an err at getGames in index.js'))
  const dataJson = JSONbig.parse(data);

  if (dataJson.game_list && dataJson.game_list.length) {
    for (let i = 0; i < dataJson.game_list.length; i++) {
      const game = dataJson.game_list[i];
...

'/api/update' 端点每 5 秒调用一次。我收到上述错误。我的 for 循环停止迭代。我希望它跳过它出错的那个,但它说我没有处理错误。我有 catch 块,甚至是错误块,我似乎无法弄清楚为什么会这样。

我也尝试过手动调用:

`https://api.steampowered.com/IDOTA2Match_570/GetTopLiveGame/v1?key=${KEY}&partner=0`

在邮递员中快速连续多次,但邮递员从不出错。所以问题出在我的代码中。我已经处理了所有错误,所以我似乎找不到我没有处理的内容。

标签: javascriptnode.jsreactjspromiseasync-await

解决方案


有几个问题:

  • 仅在您可以实际处理错误的地方捕获。在这里,您可能只想在.get回调中捕获(否则,如果您.catch在 中getGames,您将返回已解决的 Promise,而不是被拒绝的 Promise)

  • 发生错误时,不要尝试解析数据(因为它不会被填充) - 尝试解析和迭代它会导致更多错误

  • async拥有一个只有一个await立即返回的函数是没有意义的

const getGames = () => {
  return rp(`https://api.steampowered.com/IDOTA2Match_570/GetTopLiveGame/v1?key=${KEY}&partner=0`);
};

app.get('/api/update', async (req, res) => {
  const data = await getGames()
    .catch(err => {
      console.log('Houston we got an err at getGames in index.js');
      // handle error
    });
  if (!data) {
    // There was an error
    return;
  }
  const dataJson = JSONbig.parse(data);
  // rest of the code
});

推荐阅读