Ruby 2.3 / Rails - 在ubuntu 16.04更新后,net uri不再工作了

时间:2018-01-12 09:21:59

标签: ruby-on-rails ruby net-http

我以前在管理员面板中有一个正常工作的代码,检查是否存在输入的网址,如果没有,则向管理员发送友好的消息..

private

当地址(" http://www.example.com"在上面的示例中)存在时,它可以发送回200代码,但只要我有一个不存在的地址例如http://www.examplenotexistingotallyfake.com,它应该发送404代码并显示""我们有问题!回复代码:"但它失败并显示错误消息:

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

我通过打开我的Rails控制台(Rails c)验证了这一点,如果我输入:

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'

我收到相同的错误消息:

 Net::HTTP.get(URI('https://www.examplenotexistingotallyfake.com')).code

如何才能使用正确的网址而不是不存在的地址?它应该只是工作,但给我发回404代码,不应该吗?

我只能看到几天前升级到Ubutun 16.04,可能已经篡改了一些关键的dns / localhost设置作为此问题的来源,但并非100%完全确定。

修改

经过一些建议后,我现在尝试通过拯救此

来避免应用程序崩溃
 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'

但应用程序仍然因套接字错误消息而崩溃

2 个答案:

答案 0 :(得分:3)

这是正确的行为。

问题是 var[19] 并不存在于DNS条目中。

如果你看一下404:https://en.wikipedia.org/wiki/HTTP_404

的描述
  

表示客户 能够与进行通信   服务器,但服务器找不到请求的内容。

因此,为了获得404代码,您首先需要能够与相关服务器进行通信。

您可以使用chrome甚至curl仔细检查此行为,访问以下网址:examplenotexistingotallyfake.com或google.com/missing

每个人都会得到不同的结果。

卷曲:

examplenotexistingotallyfake.com

如果您希望代码的行为方式相同(即使我建议为用户提供不同的消息,您可以执行以下操作):

$ curl -I examplenotexistingotallyfake.com
curl: (6) Could not resolve host: examplenotexistingotallyfake.com

# google
curl -I google.com/missing
HTTP/1.1 404 Not Found
Content-Type: text/html; charset=UTF-8
Referrer-Policy: no-referrer
Content-Length: 1568
Date: Fri, 12 Jan 2018 09:25:27 GMT

答案 1 :(得分:0)

这不是问题,您正在寻找的网站不存在且无法访问。

因此,当您尝试直接点击它时,会发现DNS address未找到问题。这就是为什么错误: 它直接给出了socketError : getaddrinfo: Name or service not known你需要处理它。

但是如果你想要404 status code,当网站(地址)存在且该网站内的页面不存在时,你会得到它。

要获得404您的地址应该有效,如果The requested URL /examples was not found on this server.

,则会出错