2011-08-24 60 views
8

我正在嘗試使用ruby(1.8.6)中的「open-uri」處理鏈接列表中的內容,但是當我遇到不好的事情時得到一個錯誤,當一個斷開鏈接或要求身份驗證:如何在處理任何數據之前測試open-uri url

open-uri.rb:277:in `open_http': 404 Not Found (OpenURI::HTTPError) 
from C:/tools/Ruby/lib/ruby/1.8/open-uri.rb:616:in `buffer_open' 
from C:/tools/Ruby/lib/ruby/1.8/open-uri.rb:164:in `open_loop' 
from C:/tools/Ruby/lib/ruby/1.8/open-uri.rb:162:in `catch' 

C:/tools/Ruby/lib/ruby/1.8/net/http.rb:560:in `initialize': getaddrinfo: no address associated with hostname. (SocketError) 
from C:/tools/Ruby/lib/ruby/1.8/net/http.rb:560:in `open' 
from C:/tools/Ruby/lib/ruby/1.8/net/http.rb:560:in `connect' 
from C:/tools/Ruby/lib/ruby/1.8/timeout.rb:53:in `timeout' 

C:/tools/Ruby/lib/ruby/1.8/net/protocol.rb:133:in `sysread': An existing connection was forcibly closed by the remote host. (Errno::ECONNRESET) 
from C:/tools/Ruby/lib/ruby/1.8/net/protocol.rb:133:in `rbuf_fill' 
from C:/tools/Ruby/lib/ruby/1.8/timeout.rb:62:in `timeout' 
from C:/tools/Ruby/lib/ruby/1.8/timeout.rb:93:in `timeout' 

是有辦法來測試處理任何數據之前的響應(url)?

代碼:

require 'open-uri' 

smth.css.each do |item| 
open('item[:name]', 'wb') do |file| 
    file << open('item[:href]').read 
end 
end 

非常感謝

回答

23

你可以嘗試沿着

require 'open-uri' 

    smth.css.each do |item| 
    begin 
     open('item[:name]', 'wb') do |file| 
     file << open('item[:href]').read 
     end 
    rescue => e 
     case e 
     when OpenURI::HTTPError 
     # do something 
     when SocketError 
     # do something else 
     else 
     raise e 
     end 
     rescue SystemCallError => e 
     if e === Errno::ECONNRESET 
     # do something else 
     else 
     raise e 
     end 
    end 
    end 

線的東西我不知道的測試,而無需打開連接的任何方式它和嘗試,所以拯救這些錯誤將是我能想到的唯一方法。需要注意的是OpenURI :: HTTPError和SocketError都是StandardError的子類,而Errno :: ECONNRESET是SystemCallError的子類。因此,rescue => e不會捕獲Errno :: ECONNRESET。

0

我能夠通過使用條件來解決這個問題if/else語句來檢查操作的返回值「失敗」:

def controller_action 
    url = "some_API" 
    response = open(url).read 
    data = JSON.parse(response)["data"] 
    if response["status"] == "failure" 
     redirect_to :action => "home" 
    else 
     do_something_else 
    end 
end 
+0

這不會捕獲錯誤'SocketError(無法打開到jsonipsdf.com:443的TCP連接(getaddrinfo:節點名或服務器名提供,或不知道)):'' – Whitecat

相關問題