我使用以下代码查询maxmind以获取用户IP地址的地理位置。我想确保我为maxmind服务器的任何错误/超时做好准备。我应该实现某种类型的rescue
吗?如果是这样,推荐什么?
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
端
答案 0 :(得分: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