Handling Net::ReadTimeout error in HTTParty

Sam picture Sam · Oct 8, 2014 · Viewed 19.5k times · Source

I am using httparty (0.13.1) gem. I am making series of API calls using httparty. Some of my initial API calls succeeded, but the later calls fail consecutively. I have added a timeout of 180 seconds. I searched google but I can not find any solution still. I am struggling due to this for a long time.

My code:

response = HTTParty.get("http://pubapi.cryptsy.com/api.php?method=marketdatav2", timeout: 180)

Error:

A Net::ReadTimeout occurred in background at 2014-10-05 11:42:06 UTC :

I don't know whether this time out is working? I feel 180 seconds is more than enough to retrieve the response because the default timeout is 60 seconds. If I want to handle Net read timeout error, Is there a way to do it? I want to return nil if this error occurs. Or Is there a best solution to avoid happening this error?

Answer

cjspurgeon picture cjspurgeon · Feb 6, 2016

Had a similar problem with a different module, and in my case it likely succeeds if retried, so I catch the timeout and retry.

  max_retries = 3
  times_retried = 0

  begin
    #thing that errors sometimes

  rescue Net::ReadTimeout => error
    if times_retried < max_retries
      times_retried += 1
      puts "Failed to <do the thing>, retry #{times_retried}/#{max_retries}"
      retry
    else
      puts "Exiting script. <explanation of why this is unlikely to recover>"
      exit(1)
    end
  end

Left here in case someone else finds it helpful.