调用GitHub API向私有PR提交Slack评论时遇404错误求助
问题
我正在开发一款基于GitHub和Slack API的应用,需求是:当创建GitHub Pull Request(PR)时,将Slack模态框中的评论发布至该PR的变更记录中。
目前持续抛出错误:无法访问仓库,返回信息如下:
{"message":"Not Found","documentation_url":"https://docs.github.com/rest/repos/repos#get-a-repository","status":"404"}
以下是相关GitHub API代码:
async postComment( comment: string, html_url: string, userAccessToken: string, filename?: string, commitId?: string, ): Promise<void> { try { if (!(await this.verifyAccessToken(userAccessToken))) { throw new Error('Invalid or expired access token'); } const [, , , owner, repo, , pullNumber] = html_url.split('/'); if (!owner || !repo || !pullNumber) { throw new Error(`Invalid URL: ${html_url}`); } console.log( `Parsed URL: owner=${owner}, repo=${repo}, pullNumber=${pullNumber}`, ); await this.testRepoAccess(owner, repo, userAccessToken); if (!(await this.checkRepoAccess(owner, repo, userAccessToken))) { throw new Error('Cannot access the specified repository'); } if ( !(await this.checkIssueExistence( owner, repo, pullNumber, userAccessToken, )) ) { throw new Error('Cannot access the specified issue or pull request'); } const apiUrl = `https://api.github.com/repos/${owner}/${repo}/issues/${pullNumber}/comments`; console.log(`Constructed API URL: ${apiUrl}`); const response = await fetch(apiUrl, { method: 'POST', headers: { 'Content-Type': 'application/vnd.github.v3+json', Authorization: `token ${userAccessToken}`, Accept: 'application/vnd.github.v3+json', }, body: JSON.stringify({ body: comment, commit_id: commitId, path: filename, start_line: 1, position: 1, }), }); if (!response.ok) { const errorData = await response.json(); throw new Error( `GitHub API error: ${response.status} ${JSON.stringify(errorData)}`, ); } const responseData = await response.json(); console.log('Comment posted successfully:', responseData); } catch (error) { console.error('Error posting comment:', error); throw new CoefficientError('Failed to post PR comment', 'POST_COMMENT'); } }
我已验证userAccessToken有效,Slack端评论可正常发送,且拥有该组织仓库的所有者权限,但仍无法成功提交评论。请问我遗漏了什么配置或步骤?
排查方向与解决方案
1. URL解析逻辑存在致命缺陷
你通过html_url.split('/')提取owner、repo、pullNumber的方式过于脆弱:
- 若PR URL包含额外路径(如企业版自定义域名、锚点、参数),拆分后的索引会完全错误
- 示例:如果URL是
https://github.com/owner/repo/pull/123#discussion_r123456,拆分后pullNumber会变成123#discussion_r123456,直接导致API请求地址无效 - 修复方法:改用正则表达式匹配核心内容,避免索引偏移:
const match = html_url.match(/github\.com\/([^\/]+)\/([^\/]+)\/pull\/(\d+)/); if (!match) throw new Error(`Invalid URL: ${html_url}`); const [, owner, repo, pullNumber] = match;
2. Access Token权限范围或组织限制
即使你是仓库所有者,token仍可能存在权限问题:
- 检查token是否包含
repo(私有仓库)或public_repo(公有仓库)权限,无此权限会直接返回404 - 若为组织仓库,确认token是否通过了组织的SAML单点登录授权(未授权的token无法访问组织资源)
- 建议直接在GitHub token管理页重新生成一个带
repo权限的token测试
3. API请求参数冲突
你当前的请求同时混合了全局PR评论和行内评论的参数:
- GitHub API中,全局PR评论仅需
body参数;行内评论需要关联具体提交和文件路径,两类参数不能混用 - 若需求是添加全局评论,直接移除
commit_id、path、start_line、position这些参数 - 若需添加行内评论,必须确保
commit_id、path、position均为有效值,且该提交属于当前PR
4. 权限检查方法的潜在问题
404错误来自仓库访问接口,建议排查testRepoAccess和checkRepoAccess方法:
- 确认这两个方法拼接的API地址正确(应为
https://api.github.com/repos/${owner}/${repo}) - 检查方法内部是否正确处理了GitHub API的响应(比如是否误将非200状态码直接判定为无权限)
内容的提问来源于stack exchange,提问作者ayobamy
相关产品推荐
相关产品推荐

