Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/23.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby URL.parse错误_Ruby_Exception_Net Library - Fatal编程技术网

Ruby URL.parse错误

Ruby URL.parse错误,ruby,exception,net-library,Ruby,Exception,Net Library,这是我的ruby程序 require 'net/http' require 'uri' begin url = URI.parse("http://google.com") rescue Exception => err p err exit end http = Net::HTTP.new(url.host, url.port) res = http.head("/") p res.code 它工作正常,但是如果我从URL.parse()中删除http:/

这是我的ruby程序

require 'net/http'
require 'uri'

begin
    url = URI.parse("http://google.com")
rescue Exception => err
    p err
    exit
end

http = Net::HTTP.new(url.host, url.port) 
res = http.head("/")
p res.code
它工作正常,但是如果我从URL.parse()中删除http://则会出现以下错误:

/usr/lib/ruby/1.9.1/net/http.rb:1196:in `addr_port': undefined method `+' for nil:NilClass (NoMethodError) ...
from /usr/lib/ruby/1.9.1/net/http.rb:1094:in `request'
from /usr/lib/ruby/1.9.1/net/http.rb:860:in `head'
这是处理异常的正确方法吗


我知道URL可能不正确,但它应该引发异常URI::InvalidURIError,而不是接受并继续程序?

您必须特别捕获
URI::InvalidURIError
,因为它不是
异常
的后代。见:

irb(main):002:0> URI::InvalidURIError.is_a?(Exception)
=> false
因此,您的代码的修复方法是:

begin
    url = URI.parse("http://google.com")
rescue URI::InvalidURIError => err
    p err
    exit
end

如果你说
u=URI.parse('http://google.com“)
,您将返回一个
URI::HTTP
,并且
u.port
的默认值为80。如果你说
u=URI.parse('google.com')
,你会得到一个
URI::Generic
,返回
u.port
u.host

因此,当您这样做时:

url  = URI.parse('google.com')
http = Net::HTTP.new(url.host, url.port)
你真的这么做了:

http = Net::HTTP.new(nil, nil)
而且
Net::HTTP
一点也不喜欢这样。您可以尝试以下方式:

if(str.to_s.empty?)
    # complain loudly about a missing str
end
begin
    url = URI.parse(str)
    url = URI.parse('http://' + str) if !url.scheme

    if(url.scheme != 'http' && url.scheme != 'https')
        # more complaining about bad input
    end

    http = Net::HTTP.new(url.host, url.port)
    #...
rescue URI::Error => e
    # even yet more complaining
end

这类事情应该完全绕过异常,并涵盖一些您可能感兴趣的其他事情。

正确的方法不是让任何异常发生,而是事先检查您的条件。像这样:

require 'net/http'
require 'uri'

begin
    url = URI.parse("http://google.com")
rescue URI::InvalidURIError => err
    p err
    exit
end

if url.host && url.port
    http = Net::HTTP.new(url.host, url.port) 
    res = http.head("/")
    p res.code
else
        p 'Error parsing url'
end

谢谢你的回答,但是当URI.parse(“google.com”)的时候,它仍然没有捕捉到错误哦,你是对的。我没有把你的问题读清楚,我的答案并不能真正回答你的问题。尽管如此,这是对代码=)的有效修复。@iKid,我添加了另一个回答,回答了您的问题。这种方法只有在接收者满足HEAD请求时才有效。并非所有的web服务器都支持HEAD请求。@rantler,虽然这是事实,但我的方法与HEAD请求无关。我回答的这一部分是直接从OP的代码中复制过来的——我假设OP知道问题中的服务器响应HEAD请求,如果它不响应,那么这是一个完全独立的问题。这与我对这个问题的回答无关。