You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React调用GitHub Rest API仅返回‘Error’,如何获取详细错误信息?

如何获取Octokit调用GitHub API时的详细错误信息

你当前仅在catch块中打印error对象,导致无法看到具体错误细节。Octokit抛出的错误对象包含大量关键信息,可通过以下方式获取详细内容:

  • 打印完整错误结构:
    在catch中使用console.error(JSON.stringify(error, null, 2)),能展开错误对象的所有层级,包括HTTP状态码、GitHub返回的响应体、请求详情等。

  • 提取核心错误字段单独输出:
    Octokit错误对象通常包含message(错误描述)、status(HTTP状态码)、response.data(GitHub返回的具体错误详情)这些关键属性,可针对性打印:

const getRepoFiles = async (owner, repo) => {
  let path = 'composer.json';
  await octokit.request(`GET /repos/${owner}/${repo}/contents/${path}`, {
      owner: owner, // 替换写死的'OWNER',使用传入的参数
      repo: repo, // 替换写死的'REPO'
      path: path, // 替换写死的'PATH'
      headers: {
        'X-GitHub-Api-Version': '2022-11-28'
      }
  })
  .then((response) => {
      console.log(response);
      return response;
  })
  .catch((error) => {
      console.error("GitHub API 请求失败:");
      console.error("错误描述:", error.message);
      console.error("HTTP 状态码:", error.status);
      if (error.response?.data) {
          console.error("GitHub 返回详情:", error.response.data);
      }
      // 如需查看完整错误结构,可取消注释
      // console.error("完整错误对象:", JSON.stringify(error, null, 2));
  });
}
// 调用时传入实际的仓库所有者和仓库名称
getRepoFiles("你的用户名", "目标仓库名");

另外注意你代码里的两个问题:

  • getRepoFiles定义时接收owner和repo参数,但调用时未传值,会导致请求路径中的${owner}/${repo}为空
  • 请求配置里写死了owner: 'OWNER'、repo: 'REPO'、path: 'PATH',应该使用变量或传入的参数,否则会请求错误的资源路径

内容的提问来源于stack exchange,提问作者Tommy Wilkey

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.30 02:17:40