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' Does this work correctly with Exception?
I know, maybe the URL is incorrect, but should it throw a URI :: InvalidURIError exception instead of accepting and continuing the program?
If you say u = URI.parse('http://google.com') you will get URI::HTTP , and u.port will have a default value of 80. If you say u = URI.parse('google.com') , you will get back the URI::Generic using u.port will be nil , like u.host .
So when you do this:
url = URI.parse('google.com') http = Net::HTTP.new(url.host, url.port) You really do it:
http = Net::HTTP.new(nil, nil) and Net::HTTP doesn't like it at all. Instead, you can try something like this:
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 Things like this should completely circumvent the exception and cover a few other things that might interest you.
You must specifically catch the URI::InvalidURIError , since this is not a child of Exception . Cm:
irb(main):002:0> URI::InvalidURIError.is_a?(Exception) => false So, the fix for your code would be:
begin url = URI.parse("http://google.com") rescue URI::InvalidURIError => err p err exit end The correct way is to not allow any exceptions, but check your terms first. Like this:
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