2014-10-29 51 views
0

我正在使用以下代码来查询maxmind以获取用户IP地址的地理位置。我想确保我准备好了maxmind服务器的任何错误/超时。我应该执行某种类型的rescue吗?如果是这样,建议什么?Rescue和此外部API调用

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 

回答

1

拯救所有的异常:

begin 
    #your code 
rescue Timeout::Error, Errno::EINVAL, Errno::ECONNRESET, EOFError, 
    Net::HTTPBadResponse, Net::HTTPHeaderSyntaxError, Net::ProtocolError => e 
    # do something with exception 
end 

您还可以挽救一个错误的把不同的救助(用逗号多救出一个一次):

begin 
    # your code 
rescue Timeout::Error => e 

rescue Errno::EINVAL => e 

... 

end 
+0

当你说#你的代码,你是否真的意味着我所使用的所有代码将在开始和营救之间?对不起,我是这个新手。 – Abram 2014-10-29 16:57:45

+0

是的,绝对。可能引发异常的每行代码。如果您愿意,您可以将uri = Uri(...)行离开。 – iMacTia 2014-10-29 17:16:11