Read more

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

Arne Hartherz
July 02, 2021Software engineer at makandra GmbH

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.

Illustration online protection

Rails Long Term Support

Rails LTS provides security patches for old versions of Ruby on Rails (2.3, 3.2, 4.2 and 5.2)

  • Prevents you from data breaches and liability risks
  • Upgrade at your own pace
  • Works with modern Rubies
Read more Show archive.org snapshot

It may not be intuitive, but the readme says Show archive.org snapshot 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('https://httpbin.org/status/422') { |resp, req, http| resp }
=> <RestClient::Response 422 "">
>> response.code
=> 422

FYI, the http gem Show archive.org snapshot 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).

Posted by Arne Hartherz to makandra dev (2021-07-02 10:30)