Ruby 如何在处理任何数据之前测试开放uri url是否存在
我正在尝试使用ruby(1.8.6)中的“open uri”来处理链接列表中的内容,但当一个链接断开或需要身份验证时出现错误时,就会发生错误:Ruby 如何在处理任何数据之前测试开放uri url是否存在,ruby,open-uri,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:16
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'
或
或
在处理任何数据之前,是否有方法测试响应(url)
代码是:
require 'open-uri'
smth.css.each do |item|
open('item[:name]', 'wb') do |file|
file << open('item[:href]').read
end
end
需要“打开uri”
smth.css.每个do |项|
打开('item[:name],'wb')do |文件|
file您可以尝试以下方法
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
需要“打开uri”
smth.css.每个do |项|
开始
打开('item[:name],'wb')do |文件|
文件e
案例e
当OpenURI::HTTPError
#做点什么
当袜子匠
#做点别的
其他的
提高e
结束
救援系统调用程序错误=>e
如果e==Errno::ECONNRESET
#做点别的
其他的
提高e
结束
结束
结束
我不知道有什么方法可以在不打开连接并尝试的情况下测试连接,因此,挽救这些错误将是我能想到的唯一方法。需要注意的是OpenURI::HTTPError和SocketerError都是StandardError的子类,而Errno::EconReset是SystemCallError的子类。因此rescue=>e将不会捕获Errno::ECONNRESET。我能够通过使用条件if/else语句检查操作的返回值以查找“failure”来解决此问题:
这不会捕获错误SocketError(无法打开到jsonipsdf.com:443的TCP连接(提供或未知getaddrinfo:nodename或servname)):
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
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