2014-10-29 39 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