【发布时间】:2018-01-12 18:03:58
【问题描述】:
我曾经在我的管理面板中有一个工作代码,检查输入的 url 是否存在,并在不存在的情况下向管理员发送友好消息..
def get_url_response(url)
uri = URI(url)
request = Net::HTTP.get_response(uri)
return request
end
url_response = get_url_response("http://www.example.com").code
if url_response === "200" || url_response === "304"
link_to http://www.example.com, http://www.example.com, target: :blank
else
status_tag("We have a problem ! Response code: "+url_response, :class => 'red')
end
当地址(上例中的“http://www.example.com”)存在时效果很好,它说发回一个 200 代码,但只要我有一个不存在的地址,例如http://www.examplenotexistingotallyfake.com,它应该发送 404 代码并显示“”我们有问题!响应代码:”但失败并显示错误消息:
SocketError: Failed to open TCP connection to examplenotexistingotallyfake.com:443 (getaddrinfo: Name or service not known)
from /home/mreisner/.rvm/rubies/ruby-2.3.1/lib/ruby/2.3.0/net/http.rb:882:in `rescue in block in connect'
我通过打开我的 Rails 控制台 (Rails c) 验证了这一点,如果我输入:
Net::HTTP.get(URI('https://www.examplenotexistingotallyfake.com')).code
我收到同样的错误信息:
SocketError: Failed to open TCP connection to examplenotexistingotallyfake.com:443 (getaddrinfo: Name or service not known)
from /home/mreisner/.rvm/rubies/ruby-2.3.1/lib/ruby/2.3.0/net/http.rb:882:in `rescue in block in connect'
它如何适用于正确的网址而不适用于不存在的地址?它应该可以工作,但给我发回 404 代码,不是吗?
我只能看到我几天前升级到 Ubutun 16.04,这可能已经篡改了一些关键的 dns/localhost 设置作为这个问题的根源,但不是 100% 完全确定。
编辑
经过一些建议,我现在尝试通过抢救这个来避免应用崩溃
def get_url_response(url)
begin
uri = URI(url)
request = Net::HTTP.get_response(uri)
return request
rescue SocketError => e
puts "Got socket error: #{e}"
end
end
但应用程序仍然崩溃并显示套接字错误消息
【问题讨论】:
-
你确定它以前工作过吗
-
几天前我看到消息““我们有问题! " 所以我认为是但不是 100%
标签: ruby-on-rails ruby net-http