ruby – 如何在处理任何数据之前测试open-uri url
发布时间:2020-12-16 19:33:15 所属栏目:百科 来源:网络整理
导读:我正在尝试使用 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:i
我正在尝试使用
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. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |