Search code examples
ruby-on-railsjsonrest-client

Ruby on rails rest client, handling error response


I'm new in ruby (and in programming too)

I have built this code:

    #This method executing a url and give the response in json format
    def get url
      return JSON.parse(RestClient::Request.execute(method: :get, url: url))
    end

And now I'm trying to handle a case that the response code from any of the urls is not ok, and I want to replace it with error message "error"

I have tried to replace the get method with this code:

def get url
 if ((RestClient::Request.execute(method: :get, url: url)).code == 200)
    return JSON.parse(RestClient::Request.execute(method: :get, url: url))
 else
  error = "error"
    return  error.as_json
 end
end

But if the response from the url is not 200 I get an error message "406 not acceptable" instead of "error"

Thanks in advance


Solution

  • RestClient::Request will raise an exception when it receives error response (response code other than 2xx/3xx):

    • for result codes between 200 and 207, a RestClient::Response will be returned
    • for result codes 301, 302 or 307, the redirection will be followed if the request is a GET or a HEAD
    • for result code 303, the redirection will be followed and the request transformed into a GET
    • for other cases, a RestClient::Exception holding the Response will be raised; a specific exception class will be thrown for known error codes
    • call .response on the exception to get the server's response

    Documentation

    You should handle that exception:

    def get url
      result = RestClient::Request.execute(method: :get, url: url)
      JSON.parse(result)
    rescue RestClient::Exception
      "error" # no need to call 'as_json'
    end
    

    More on Ruby exception handling:

    Ruby Exceptions