views:

17

answers:

1

I'm using Restclient (HTTP and REST client for Ruby) to check if a URL is valid. The Restclient response wraps Ruby's Net::HTTPResponse.

p (RestClient.get "www.google.com").code == 200 # outputs true

The problem is, if the URL isn't valid, the app crashes:

p (RestClient.get "test").code == 200 

SocketError (getaddrinfo: nodename nor servname provided, or not known):
  /usr/local/lib/ruby/1.8/net/http.rb:560:in `initialize'
  /usr/local/lib/ruby/1.8/net/http.rb:560:in `open'
  /usr/local/lib/ruby/1.8/net/http.rb:560:in `connect'
  /usr/local/lib/ruby/1.8/timeout.rb:53:in `timeout'
  /usr/local/lib/ruby/1.8/timeout.rb:93:in `timeout'
  /usr/local/lib/ruby/1.8/net/http.rb:560:in `connect'
  /usr/local/lib/ruby/1.8/net/http.rb:553:in `do_start'
  /usr/local/lib/ruby/1.8/net/http.rb:542:in `start'

I don't think I want to use a regex to check if the URL looks ok because I haven't found one that covers all possible URLs that would return a HTTP response code of 200 (ie. no http/https/www etc). How can I catch this error instead of it causing the site to crash? Thanks for reading.

A: 

Try this blog article about url validation.

Thomas