簡體   English   中英

通過對等錯誤從連接重置中解救並重試

[英]rescue from connection reset by peer error and retry

我遇到的外部服務會進行一些密碼加密並返回一些信息。

現在,如果我想生成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

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

結束

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM