如何处理 YouTube Data API v3 错误 429,请求过多(资源已耗尽)

问题描述 投票:0回答:1

我正在尝试在 React 应用程序中使用 YouTube Data API v3 在 YouTube 上创建播放列表。但是,我遇到 429 错误,表明我的资源已耗尽。为了解决这个问题,我实施了具有随机延迟的指数退避策略,但我仍然达到了速率限制。这是我当前的实现:

我的代码

``import axios from "axios";

// Helper function to generate a random delay within a range
const getRandomDelay = (min, max) =>
  Math.floor(Math.random() * (max - min + 1)) + min;

const exponentialBackoff = async (fn, retries = 3, delay = 1000) => {
  try {
    return await fn();
  } catch (error) {
    if (
      retries > 0 &&
      error.response &&
      (error.response.status === 403 || error.response.status === 429)
    ) {
      const randomDelay = getRandomDelay(delay, delay * 2);
      await new Promise((resolve) => setTimeout(resolve, randomDelay));
      return exponentialBackoff(fn, retries - 1, delay * 2);
    } else {
      throw error;
    }
  }
};

export const createYouTubePlaylist =
  (playlistName) => async (dispatch, getState) => {
    const { youtubeAccessToken } = getState().auth;

    const createPlaylist = async () => {
      try {
        const response = await axios.post(
          "https://www.googleapis.com/youtube/v3/playlists",
          {
            snippet: {
              title: playlistName, // Remove quotes around playlistName
              description: "Playlist created from Spotify",
            },
            status: {
              privacyStatus: "public",
            },
          },
          {
            headers: {
              Authorization: `Bearer ${youtubeAccessToken}`,
              Accept: "application/json",
            },
            params: {
              part: "snippet,status",
            },
          }
        );
        console.log("Created Playlist:", response.data);
        return response.data;
      } catch (error) {
        console.error("Error creating YouTube playlist:", error);
        throw error; // Rethrow the error to handle it outside
      }
    };

    return exponentialBackoff(createPlaylist)
      .then((data) => {
        console.log("Playlist created successfully:", data);
        return data;
      })
      .catch((error) => {
        console.error("Error creating YouTube playlist:", error);
        return null; // Return null or handle the error as needed
      });
  };`
`

错误:429 资源已耗尽

  1. 我的指数退避策略是否正确实施来处理 429 错误?
  2. 我可以采取任何其他步骤来避免达到速率限制吗?
  3. 是否有更好的方法来处理这些错误或使用 YouTube 数据 API v3 的推荐方法?
javascript reactjs axios youtube-data-api
1个回答
0
投票

你能解决这个问题吗?我也遇到同样的问题

最新问题
© www.soinside.com 2019 - 2024. All rights reserved.