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

我正在尝试使用 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'

要么

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

非常感谢

解决方法

你可以试试一下
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.

相关文章

validates:conclusion,:presence=>true,:inclusion=>{...
一、redis集群搭建redis3.0以前,提供了Sentinel工具来监控各...
分享一下我老师大神的人工智能教程。零基础!通俗易懂!风趣...
上一篇博文 ruby传参之引用类型 里边定义了一个方法名 mo...
一编程与编程语言 什么是编程语言? 能够被计算机所识别的表...
Ruby类和对象Ruby是一种完美的面向对象编程语言。面向对象编...