我想知道是否有人可以提供帮助,以及该问题是否特定于last.fm(也许不是最大的API)。
我已经在我的应用程序中构建了一个专辑搜索功能,该功能采用了两个参数 - 专辑和艺术家。现在,如果有结果,这将返回一张专辑,但是在没有结果的情况下 - 如果只是在字段中键入gibberish -rails在尝试运行 uri.open时会出现404错误(404)( URL).READ
。
我不太了解的(我对此很新),当我在搜索引擎中运行相同的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
感谢您的任何指示。
I wonder if anyone can help, and if the issue is specific to Last.fm (perhaps not the greatest of APIs).
I've built an album search feature into my app that takes two parameters - album and artist. Now, this returns an album just fine if there's a result, but in the instances that there isn't a result - if just type gibberish into the fields - Rails breaks with a 404 error when trying to run URI.open(url).read
.
What I don't quite understand (and I am fairly new at this), is that when I run the same API call url in my search engine, with the gibberish, I do get a JSON response:
// https://ws.audioscrobbler.com/2.0/?method=album.getinfo&api_key=xxxxxxx&artist=akjsdhkasd&album=hdkuahd&format=json
{
"message": "Album not found",
"error": 6
}
So, I don't understand why I'm getting a 404 error when it runs in my code.
Is there any way that I can rescue this, so that I can just render a 'no result', rather than crashing the entire site?
Not sure my code adds much to the picture, but this is where I run the 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
Thanks for any pointers.
发布评论
评论(1)
据我了解,您正在使用
Open-uri
来达到此服务。如果您想Rescue
在此过程中的一个例外,您可以尝试这样的事情:*我只返回一个字符串,但您可以实现适合您目的的适当申报表。
我不确定是否可以使用此策略挽救特定的
404-找不到
错误。但是,您可以查看'net/http' 或其他http客户端库(, typhoeus 等。From what I understood, you are using
open-uri
to reach this service. If you want torescue
an exception in this process you can try something like this:*I'm returning just a string but you can implement an appropriate return that fits your purpose.
I'm not sure if it's possible to rescue specific
404 - Not Found
errors using this strategy. But, you can take a look into'net/http'
or other HTTP Client Libraries (httparty, typhoeus, etc..) to try different approaches if you want..