简体   繁体   English

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

[英]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" 现在我正在尝试处理一个案例,任何网址的响应代码都不正常,我想用错误消息“error”替换它

I have tried to replace the get method with this code: 我试图用这段代码替换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

But if the response from the url is not 200 I get an error message "406 not acceptable" instead of "error" 但是如果来自网址的响应不是200,我收到错误消息“406不可接受”而不是“错误”

Thanks in advance 提前致谢

RestClient::Request will raise an exception when it receives error response (response code other than 2xx/3xx): RestClient::Request会在收到错误响应时引发异常(响应代码不是2xx / 3xx):

  • for result codes between 200 and 207, a RestClient::Response will be returned 对于200到207之间的结果代码,将返回RestClient :: Response
  • for result codes 301, 302 or 307, the redirection will be followed if the request is a GET or a HEAD 对于结果代码301,302或307,如果请求是GET或HEAD,则将遵循重定向
  • for result code 303, the redirection will be followed and the request transformed into a GET 对于结果代码303,将遵循重定向并将请求转换为GET
  • for other cases, a RestClient::Exception holding the Response will be raised; 对于其他情况,将引发一个包含Response的RestClient :: Exception; a specific exception class will be thrown for known error codes 将针对已知错误代码抛出特定的异常类
  • call .response on the exception to get the server's response 在异常上调用.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异常处理的更多信息

Ruby Exceptions Ruby例外

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM