Ruby on rails Rescue和此外部API调用

Ruby on rails Rescue和此外部API调用,ruby-on-rails,Ruby On Rails,我正在使用以下代码查询maxmind,以查找用户IP地址的地理位置。我想确保我已经为maxmind服务器的任何错误/超时做好了准备。我是否应该实施某种类型的救援?如果是,建议是什么 uri = URI("https://geoip.maxmind.com/geoip/v2.1/city/#{request.remote_ip}?pretty") Net::HTTP.start(uri.host, uri.port, :use_ssl => uri.scheme == 'https',

我正在使用以下代码查询maxmind,以查找用户IP地址的地理位置。我想确保我已经为maxmind服务器的任何错误/超时做好了准备。我是否应该实施某种类型的
救援
?如果是,建议是什么

uri = URI("https://geoip.maxmind.com/geoip/v2.1/city/#{request.remote_ip}?pretty")

Net::HTTP.start(uri.host, uri.port,
  :use_ssl => uri.scheme == 'https', 
  :verify_mode => OpenSSL::SSL::VERIFY_NONE) do |http|

  request = Net::HTTP::Get.new uri.request_uri
  request.basic_auth 'USER_ID', 'KEY'

  response = http.request request # Net::HTTPResponse object

  if response.kind_of? Net::HTTPSuccess
    location_hash = JSON.parse(response.body)
  end
end

结束营救所有异常:

begin
    #your code
rescue Timeout::Error, Errno::EINVAL, Errno::ECONNRESET, EOFError,
    Net::HTTPBadResponse, Net::HTTPHeaderSyntaxError, Net::ProtocolError => e
    # do something with exception
end
您还可以通过放置不同的救援来救援单个错误(使用逗号一次救援多个错误):


当你说#你的代码时,你的意思是我在上面使用的所有代码都会介于begin和rescue之间吗?对不起,我是新手。是的,当然。可能引发异常的每一行代码。如果愿意,可以将uri=uri(…)行保留。
begin
    # your code
rescue Timeout::Error => e

rescue Errno::EINVAL => e

...

end