Search code examples
rubyhttpclient

Is there a way to get response on error with HTTPClient in Ruby?


I'm using the HTTPClient ruby library for making some basic http requests to a REST service I have develop and im wondering now how can I get the response from the service when an error occurred (a status code like 400 or 500 is returned from the service).

What my service does is return the stock of a product in a center, so it takes two parameters (in the url): a product id and a center id. When I call this service passing correct product and center ids the service returns me a 200 - OK status and the stock of the product (for example, 8.0 indicating there are 8 units of the product in that center). However, if I pass a wrong product id (one that is not in our database) the service returns 400 - Bad Request and an error message indicating that the id does not exists.

So I have a method like the following in Ruby

def stock(product, location)
   response = @client.get_content("stock/#{product}/#{location}")
end                  

@client is an instance created with HTTPClient.new that I have configured. On passing ''right'' arguments it returns me what I want so it is well configured

My problem now is that when the service returns an error status code an HTTPClient::BadResponseError exception is thrown and I'm not able to retrieve this error in the response variable.

Is there a way to get the response from the service, no matter which status code it returns? I tried using begin...rescue and I can get some information like the status code and the reason phrase, but not the content of the response (the error message)


Solution

  • You're using get_content which skips a few steps and returns the content. Instead step back and use get which will return a more complete response structure that includes, among other things, the status field you want:

    def stock(product, location)
      response = @client.get("stock/#{product}/#{location}")
    
      body = response.body
      status = response.status
    end