Ruby on rails rest client, handling error response
Asked Answered
F

1

5

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

Flagg answered 8/8, 2015 at 15:9 Comment(0)
H
7

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

Helladic answered 8/8, 2015 at 16:4 Comment(1)
Perfect! def get url result = RestClient::Request.execute(method: :get, url: url) JSON.parse(result) rescue RestClient::Exception => e e.response.body e.response.code endHammers

© 2022 - 2024 — McMap. All rights reserved.