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 UI/UX Design

UI/UX Design by makandra brand

We make sure that your target audience has the best possible experience with your digital product. You get:

  • Design tailored to your audience
  • Proven processes customized to your needs
  • An expert team of experienced designers
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)