Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby URL.parse error

Here is my ruby program

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

It works fine, however if I remove http:// from URL.parse(), It gives me this error:

/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'

Is it the correct way to handle Exception ?

I know maybe the URL is not correct, but It should raise an exception URI::InvalidURIError instead of accepting and continue the program ?

like image 548
w00d Avatar asked Dec 07 '22 19:12

w00d


1 Answers

If you say u = URI.parse('http://google.com'), you'll get a URI::HTTP back and the u.port will have a default of 80. If you say u = URI.parse('google.com'), you'll get a URI::Generic back with the u.port will be nil as will u.host.

So, when you do this:

url  = URI.parse('google.com')
http = Net::HTTP.new(url.host, url.port)

You're really doing this:

http = Net::HTTP.new(nil, nil)

and Net::HTTP doesn't like that very much at all. You could try something like this instead:

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

That sort of thing should bypass the exception completely and cover a few other things that you might be interested in.

like image 160
mu is too short Avatar answered Dec 21 '22 02:12

mu is too short