2

In my Rails app I am making various API calls like this one:

class SearchFacebook

  FALLBACK_STARS = 5.0

  def self.call
    begin
      url = "https://graph.facebook.com/v2.12/#{FACEBOOK_PAGE_ID}"
      response = RestClient.get(url, :params => {:access_token => FACEBOOK_ACCESS_TOKEN, :fields => "overall_star_rating"})
      json = JSON.parse(response)
      stars = json["overall_star_rating"]
    rescue RestClient::ExceptionWithResponse => error
      stars = FALLBACK_STARS
    end
    {:stars => stars}
  end

end

The problem is that I am running my app in my local environment a lot of the time. When there's no Internet connection available (which happens a lot to me, don't ask why), I get the following error:

SocketError. Failed to open TCP connection to api.facebook.com:443 (getaddrinfo: nodename nor servname provided, or not known)

How can I rescue from being offline?

I checked RestClient documentation already but to no avail. Thanks for any help.

Tintin81
  • 9,821
  • 20
  • 85
  • 178
  • 1
    Can you use a blanket `rescue => e` and use byebug to inspect the exception being raised. You could then rescue that error if in a development environment. – Michael Brawn May 20 '18 at 18:27

2 Answers2

2

Can you use a blanket rescue => e and use byebug to inspect the exception being raised. You could then rescue that error if in a development environment.

There are some other options mentioned here Check if Internet Connection Exists with Ruby?

Michael Brawn
  • 303
  • 2
  • 9
0

OK, I solved this by simply rescuing from a SocketError:

rescue SocketError, RestClient::ExceptionWithResponse => error

I found this answer quite helpful.

Tintin81
  • 9,821
  • 20
  • 85
  • 178