【问题标题】:Rails 6 how to handle 404 from Github file fetching using OctokitRails 6 如何使用 Octokit 从 Github 文件获取中处理 404
【发布时间】:2021-11-18 16:23:25
【问题描述】:

在我的 Rails 6 应用程序中,我试图实现负责从不同的 Github 存储库获取文件的功能。代码应尝试从 GitHub 获取文件 name.jsonname.master.json(因为文件可能是主 json 或标准 json)。

代码如下:

#lib/github_client.rb

module GithubClient
  extend self

  def fetch_file(file_name)
    if (response = translate(file_name)).success?
      response
    else
      translate(file_name, master: true)
    end
  end
  
  private

  def client
    @client ||= Octokit::Client.new(access_token: Rails.application.credentials.github[:access_token])
  end

  def translate(file_name, master: false)
    return client.contents('user/my-repo-name', path: "#{file_name}.master.json") if master == 'true'

    client.contents('user/my-repo-name', path: "#{file_name}.json")
  end
end

if (response = translate(file_name)).success?不起作用,因为如果没有文件,例如book.master.json 会返回:

Octokit::NotFound (GET https://api.github.com/repos/user/my-repo-name/book.json: 404 - 未找到 // 请参阅:https://docs.github.com/rest/reference/repos#get-repository-content)

如何检查此响应的状态,以便在必要时搜索另一个文件?

【问题讨论】:

    标签: ruby-on-rails ruby octokit


    【解决方案1】:

    我不确定是否有 #exists? 方法或类似方法,这可能是更好的解决方案(我在文档中看不到这样的方法!...),但你总是可以拯救异常,以便优雅地处理预期的失败。例如:

      client.contents('user/my-repo-name', path: "#{file_name}.json")
    rescue Octokit::NotFound
      client.contents('user/my-repo-name', path: "#{file_name}.master.json")
    

    请注意,您当前的代码也略有错误,因为您正在检查 if master == 'true' -- 但 master布尔值 (true / false),而不是 String ("true")。

    true != "true"
    

    【讨论】:

      猜你喜欢
      • 2015-11-17
      • 2019-10-17
      • 2014-01-25
      • 2021-01-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-08-28
      相关资源
      最近更新 更多