Something Similar

About Jeff Hodges
Atom Feed
Archive

OpenURI, Exceptions and HTTP Status Codes

If you’ve needed the numeric HTTP status code from a connection created with either open-uri’s or rest-open-uri’s open method, you’ve probably noticed that OpenURI::HTTPError is raised on any thing other than a 2xx or 1xx status code and that the docs don’t really lay out how to get to the status code in that error. Some of you may have hacked up a the_error.to_s[0..2] solution, but that is bad and terrible. Don’t do it. Here’s the right way. (Good luck remembering it after a few weeks away, however.)

require 'open-uri' # or 'rest-open-uri'
begin
  io_thing = open(some_http_uri)
  
  # The text of the status code is in [1]
  the_status = io_thing.status[0]

rescue OpenURI::HTTPError => the_error
  # some clean up work goes here and then..

  the_status = the_error.io.status[0] # => 3xx, 4xx, or 5xx
  
  # the_error.message is the numeric code and text in a string
  puts "Whoops got a bad status code #{the_error.message}"
end
do_something_with_status(the_status)

There you go. You’ll notice that neither open-uri nor rest-open-uri use the Net:HTTP response classes like it claims you should in these cases, but you can map to them with the numeric status codes. All you need are the CODE_CLASS_TO_OBJ and CODE_TO_OBJ hashes defined in Net::HTTPResponse. The latter hash is probably preferable.

Update: Edited for stupidity.