almo
almo

Reputation: 6367

Trying to rescue HTTParty connection error in Rails 5

I am using Rails 5 and HTTParty.

Problem is that if the API is down for some reason my app crashes. I want to handle this case and have found several solutions but did not make them work.

What I did is:

begin
   api = HTTParty.get(URL)
rescue HTTParty::Error
   puts('API not available')
end

What I hoped is that if the API is down or if I use an invalid URL it would not give me an internal server error but tell me the the API is not available and continue with the code.

But instead it gives and internal server error:

SocketError (Failed to open TCP connection to URL (getaddrinfo: nodename nor servname provided, or not known)):

How can I make sure that this does not happen?

Upvotes: 1

Views: 2688

Answers (2)

AFOC
AFOC

Reputation: 844

I had this same issue, but rescuing from HTTParty::Error did nothing. My actual error was always Errno::ECONNREFUSED, thus the following is what solved it for me:

begin
  api = HTTParty.get(URL)
rescue Errno::ECONNREFUSED
  puts('API not available')
end

Upvotes: 1

AntonTkachov
AntonTkachov

Reputation: 1784

It looks that you just rescue not the same error you really get.

begin
   api = HTTParty.get(URL)
rescue HTTParty::Error, SocketError => e
   puts('API not available')
end

Keep in mind that all your code, that is executed after this rescue should take into account that your response can be blank

Upvotes: 4

Related Questions