Check Ruby HTTP response for success

You can take advantage of Ruby's case statement which idiomatically performs class comparisons, thanks to its use of === under the hood.

Here's an example from a JSON client that catches particular errors but otherwise just returns the server's message:

  case response
    when Net::HTTPSuccess
      JSON.parse response.body
    when Net::HTTPUnauthorized
      {'error' => "#{response.message}: username and password set and correct?"}
    when Net::HTTPServerError
      {'error' => "#{response.message}: try again later?"}
    else
      {'error' => response.message}
  end

Note above Net::HTTPResponse parent classes (e.g. Net::HTTPServerError) work too.


For Net::HTTP, yes, checking the class of the response object is the way to do it. Using kind_of? (aliased also as is_a?) is a bit clearer (but functionally equivalent to using <):

response.kind_of? Net::HTTPSuccess

Calling value on response will also raise a Net::HTTPError if the status code was not a successful one (what a poorly named method…).

If you can, you may want to consider using a gem instead of Net::HTTP, as they often offer better APIs and performance. Typhoeus and HTTParty are two good ones, among others.

Tags:

Ruby

Net Http