如何在处理任何数据之前测试open-uri url

Kos*_*tas 9 ruby open-uri

我正在尝试使用ruby(1.8.6)中的"open-uri"处理链接列表中的内容,但是当一个链接断开或需要身份验证时我收到错误时会发生错误:

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' 
Run Code Online (Sandbox Code Playgroud)

要么

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'
Run Code Online (Sandbox Code Playgroud)

要么

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'
Run Code Online (Sandbox Code Playgroud)

有没有办法在处理任何数据之前测试响应(url)?

代码是:

require 'open-uri'

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

非常感谢

dog*_*unk 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
Run Code Online (Sandbox Code Playgroud)

我不知道在没有打开和尝试的情况下测试连接的任何方法,因此拯救这些错误将是我能想到的唯一方法.需要注意的是,OpenURI :: HTTPError和SocketError都是StandardError的子类,而Errno :: ECONNRESET是SystemCallError的子类.所以rescue => e不会捕获Errno :: ECONNRESET.