Posted over 1 year ago. Visible to the public.

How to avoid raising RestClient exceptions for 4xx or 5xx results

When using RestClient to make an HTTP request, it will raise an exception when receiving a non-successful response.
HTTP status codes like 422 or 403 might be totally expected when talking to APIs, so plastering your code with rescue RestClient::Exception or similar can feel annoying.

It may not be intuitive, but the readme says Archive you can also pass a block to methods like RestClient.get or RestClient::Request.execute. In that case, RestClient will not raise an error, but call the block with 3 block arguments:

  • a RestClient::Response
  • the RestClient::Request for your request
  • an underlying Net::HTTP result, e.g. Net::HTTPUnprocessableEntity

The called method will then return the return statement of the block.

So this will just return the response object of a request so we can assign it to a variable:

>> response = RestClient.get('') { |resp, req, http| resp } => <RestClient::Response 422 ""> >> response.code => 422

FYI, the http gem Archive is a great alternative to RestClient which behaves like that by default and has a well-designed API in general (much better than RestClient, in my opinion).

Growing Rails Applications in Practice
Check out our new e-book:
Learn to structure large Ruby on Rails codebases with the tools you already know and love.

Owner of this card:

Arne Hartherz
About this deck:
We are makandra and do test-driven, agile Ruby on Rails software development.
License for source code
Posted by Arne Hartherz to makandra dev
This website uses short-lived cookies to improve usability.
Accept or learn more