【问题标题】:UnhandledPromiseRejectionWarning, but I am handling errors?UnhandledPromiseRejectionWarning,但我正在处理错误?
【发布时间】:2020-05-07 00:48:03
【问题描述】:

我收到以下错误:

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`

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

【问题讨论】:

    标签: javascript node.js reactjs promise async-await


    【解决方案1】:

    有几个问题:

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

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

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

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

    【讨论】:

    • 感谢您的澄清,这确实有助于提高我对错误处理的理解。但是,我很困惑为什么我的 getGames 函数出错了?我在邮递员中连续多次手动执行此 API 调用,但我每次都收到数据。然而在我的应用程序中却出错了。
    • 因为发生错误时,不要尝试解析数据(因为它不会被填充)——尝试解析和迭代会导致更多错误 - 所以,如果没有数据(确保不要从.catch 返回任何内容),返回
    • 另请注意,JSON 表示法是一种用于以字符串格式表示对象或数组的格式。反序列化后,您只有一个普通对象或数组,不是 JSON - 可能有助于将变量名称从 dataJson 更改为 dataObj,或类似的东西
    猜你喜欢
    • 1970-01-01
    • 2019-10-27
    • 2020-11-22
    • 2019-12-10
    • 2019-05-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多