Search code examples
ruby-on-railsrubynet-http

rescue from connection reset by peer error and retry


I am hitting an external service which does some password encryption and returns couple of things.

Now if I want to generate 50 passwords we run this function in a loop 50 times

def self.encrypt_password(password)
    retries = 2
    uri = URI
    params = Base64.encode64(password)
    uri.query = URI.encode("Source=#{params}")
    begin    
      retries.times.each do
        res = Net::HTTP.get_response(uri)
        if res.is_a?(Net::HTTPSuccess)
          obj = JSON.parse(res.body)
          pw = Base64.decode64(obj["Data"])
          ps = Base64.decode64(obj["Key"])

          pws = Iconv.iconv('ascii', 'utf-16', pws)
          return pwe,pws[0]
        end 
      end
    rescue
      raise "Error generating pws: #{$!}"
    end
  end

But the problem, i am encountering is that there are occasions when the service just returns the following error in the middle of a loop and exits:

"Connection reset by Peer error"

My question is how do I rescue from that error and retry a few times without breaking the flow of the program?

Or can someone recommend alternate solutions to my problem?

NOTE: I am using ruby on rails 2 and ruby 1.8.x


Solution

  • Ruby has the retry method, that can be used in the rescue clause.

    It just runs the current method again, so you can use a counter to limit the number of retries:

    def self.encrypt_password(password)
      retries = 2
      uri = URI
      params = Base64.encode64(password)
      uri.query = URI.encode("Source=#{params}")
      retries.times.each do
        res = Net::HTTP.get_response(uri)
        if res.is_a?(Net::HTTPSuccess)
          obj = JSON.parse(res.body)
          pw = Base64.decode64(obj["Data"])
          ps = Base64.decode64(obj["Key"])
    
          pws = Iconv.iconv('ascii', 'utf-16', pws)
          return pwe,pws[0]
        end 
      end
    rescue SomeExceptionType
      if retries > 0
        retries -= 1
        retry
      else
        raise "Error generating pws: #{$!}"
      end
    end
    

    end