Search code examples
ruby-on-railsrubyapihttp-status-code-404

Rails App Breaks with 404 Error when Last.fm API Call Returns Nothing


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.


Solution

  • From what I understood, you are using open-uri to reach this service. If you want to rescue an exception in this process you can try something like this:

    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
    

    *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..