Rainforest is built on open source and we’ve been doing our best to contribute back to it. I extracted Http::Exceptions from the main Rainforest application, since it’s a pain that we spent a lot of time dealing with and we figured it could be useful for the broader community.

Click here to check it out on GitHub.

Sometimes small things can end up being a huge time saver and lead to significantly safer and cleaner code – I hope you find it as useful as we do!

What is it for?

If you’re using a library such as the excellent HTTParty, you still have to deal with various types of exceptions. In an ideal world, the return code of the HTTP request would be the sole indicator of failures, but HTTP libraries can raise a large number of exceptions (such as SocketError or Net::ReadTimeout) that you need to handle.

Http::Exceptions provides an easy way to rescue exceptions that get thrown by your HTTP library and a way to raise exceptions on unexpected HTTP status codes.

Http::Exceptions converts any error that might be raised by your HTTP library and wrap it in a Http::Exceptions::HttpException. This results in much easier to understand and more robust code.

Let’s look at some examples:

Only rescue raised exceptions:

response = Http::Exceptions.wrap_exception do 
  HTTParty.get "https://www.google.com"
end

Raise an exception is the return code of the API call is not 2XX:

response = Http::Exceptions.wrap_and_check do
  HTTParty.get "https://www.google.com"
end

You can then rescue the exception in the following way:

begin
  response = Http::Exceptions.wrap_and_check do
    HTTParty.get "http://www.google.com"
  end
rescue Http::Exceptions::HttpException => e
  # ...
end

Support

Currently, this only has been tested with HTTParty. It should however work with any library that delegates to the Ruby http library.

Enjoy!