通过对等错误抢救连接重置并重试

时间:2015-04-03 16:58:26

标签: ruby-on-rails ruby net-http

我正在点击一个外部服务,它会进行一些密码加密并返回几件事。

现在,如果我想生成50个密码,我们将循环运行此函数50次

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

但问题是,我遇到的情况是,有时服务只是在循环中间返回以下错误并退出:

  

“通过对等错误重置连接”

我的问题是如何在不破坏程序流程的情况下挽救该错误并重试几次?

或者有人可以为我的问题推荐替代解决方案吗?

注意:我在rails 2和ruby 1.8.x上使用ruby

1 个答案:

答案 0 :(得分:1)

Ruby有retry方法,可以在rescue子句中使用。

它只是再次运行当前方法,因此您可以使用计数器来限制重试次数:

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

相关问题