api - 当 Last.fm API 调用没有返回任何内容时,Rails 应用程序因 404 错误而中断

我想知道是否有人可以提供帮助,以及该问题是否特定于 Last.fm(也许不是 APIs 中最大的问题)。

我在我的应用程序中构建了一个专辑搜索功能,它采用两个参数——专辑和艺术家。现在,如果有结果,这将返回一张专辑就好了,但是在没有结果的情况下——如果只是在字段中输入乱码——Rails 在尝试运行 URI.open(url).read 时会出现 404 错误。

我不太明白(而且我对此很陌生)是,当我在搜索引擎中运行相同的 API 调用 url 时,我确实收到了 JSON 响应:

// https://ws.audioscrobbler.com/2.0/?method=album.getinfo&api_key=xxxxxxx&artist=akjsdhkasd&album=hdkuahd&format=json

{
  "message": "Album not found",
  "error": 6
}

所以,我不明白为什么在我的代码中运行时会出现 404 错误。

有什么办法可以挽救这个,这样我就可以呈现“无结果”,而不是让整个网站崩溃?

不确定我的代码给图片增加了多少,但这是我运行 URI 的地方:

def get_album(artist, album)
    album = ERB::Util.url_encode(album)
    artist = ERB::Util.url_encode(artist)
    url = "https://ws.audioscrobbler.com/2.0/?method=album.getinfo&api_key=xxxx&artist=#{artist}&album=#{album}&format=json"
    serialized = URI.open(url).read
    JSON.parse(serialized, object_class: OpenStruct).album
  end

感谢您的任何指示。

回答1

据我了解,您正在使用 open-uri 来访问此服务。如果你想 rescue 在这个过程中出现异常,你可以尝试这样的事情:

def get_album(artist, album)
  album = ERB::Util.url_encode(album)
  artist = ERB::Util.url_encode(artist)
  url = "https://ws.audioscrobbler.com/2.0/?method=album.getinfo&api_key=xxxx&artist=#{artist}&album=#{album}&format=json"
  serialized = URI.open(url).read
  JSON.parse(serialized, object_class: OpenStruct).album
rescue OpenURI::HTTPError
  "Error when trying to fetch album information"
end

*我只返回一个字符串,但您可以实现适合您目的的适当返回。

我不确定是否可以使用此策略来挽救特定的 404 - Not Found 错误。但是,您可以查看 https://ruby-doc.org/stdlib-2.7.1/libdoc/net/http/rdoc/Net/HTTP.html 或其他 HTTP 客户端库(https://github.com/jnunemaker/httpartyhttps://github.com/typhoeus/typhoeus 等)以如果你想尝试不同的方法..

相似文章

twilio - DevTools 无法加载源 map

我知道Chrome开发工具中有很多关于这些警告的帖子。对于所有这些,解决方案是关闭通知“启用javascript源maps”和“启用CSS源maps”。我想知道的是如何解决这个问题,以及导致这些警告的...

随机推荐

最新文章