Ruby 在 rails 休息客户端,处理错误响应

Ruby on rails rest client, handling error response

我是 ruby 的新手(也是编程方面的新手)

我构建了这段代码:

    #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

现在我正在尝试处理来自任何 url 的响应代码不正确的情况,我想将其替换为错误消息 "error"

我尝试用这段代码替换 get 方法:

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

但是如果 url 的响应不是 200,我会收到错误消息“406 不可接受”而不是 "error"

提前致谢

RestClient::Request收到错误响应时会抛出异常(响应码不是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

您应该处理该异常:

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

有关 Ruby 异常处理的更多信息:

Ruby Exceptions