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 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).

Arne Hartherz Almost 3 years ago