39

我最近从 Ruby 的 Net:HTTP 类切换到了 rest-client 1.6.7。

我发现形成请求要容易得多,但与 Net:HTTP 请求不同,当 rest-client 得到 200 以外的任何内容时,请求就会终止。我尝试在 RestClient.get 之后直接放置一个断点,但它永远不会被击中 - 所以我做错了什么。

def get_member_using_card
  resource = "#{@settings_app_uri}api/v1/card/#{self.member_card_num}?token=#{@settings.api_key}"
  response = RestClient.get resource
  if response.code == 200 
    card = JSON.parse(response.body)
    self.customer_id = card['card']['customer_id']
  else
    return 0
  end
end

这导致了这个堆栈跟踪:

RestClient::ResourceNotFound - 404 Resource Not Found:
        /Users/tim/.rvm/gems/ruby-1.9.2-p290/gems/rest-client-1.6.7/lib/restclient/abstr
act_response.rb:48:in `return!'
        /Users/tim/.rvm/gems/ruby-1.9.2-p290/gems/rest-client-1.6.7/lib/restclient/reque
st.rb:230:in `process_result'
        /Users/tim/.rvm/gems/ruby-1.9.2-p290/gems/rest-client-1.6.7/lib/restclient/reque
st.rb:178:in `block in transmit'
        /Users/tim/.rvm/rubies/ruby-1.9.2-p290/lib/ruby/1.9.1/net/http.rb:627:in `start'
        /Users/tim/.rvm/gems/ruby-1.9.2-p290/gems/rest-client-1.6.7/lib/restclient/reque
st.rb:172:in `transmit'
        /Users/tim/.rvm/gems/ruby-1.9.2-p290/gems/rest-client-1.6.7/lib/restclient/reque
st.rb:64:in `execute'
        /Users/tim/.rvm/gems/ruby-1.9.2-p290/gems/rest-client-1.6.7/lib/restclient/reque
st.rb:33:in `execute'
        /Users/tim/.rvm/gems/ruby-1.9.2-p290/gems/rest-client-1.6.7/lib/restclient.rb:68
:in `get'

有人可以告诉我如何正确评估响应代码并防止此异常发生...?

4

5 回答 5

58

请参阅http://rubydoc.info/gems/rest-client/上的标题异常

  • 对于 200 到 207 之间的结果代码,将返回 RestClient::Response
  • 对于结果代码 301、302 或 307,如果请求是 get 或 head,则将遵循重定向
  • 对于结果代码 303,将遵循重定向并将请求转换为 get
  • 对于其他情况,将引发包含响应的 RestClient::Exception,将抛出特定的异常类以获取已知错误代码

RestClient.get 'http://example.com/resource'
➔ RestClient::ResourceNotFound: RestClient::ResourceNotFound`

begin
  RestClient.get 'http://example.com/resource'
rescue => e
  e.response
end
➔ 404 Resource Not Found | text/html 282 bytes
于 2012-10-17T09:04:37.283 回答
25

同样在@wich 指出的同一个文档中,您可以将一个块传递给 RestClient.get ,这样它就不会在非 200 响应代码上引发异常:

# Don't raise exceptions but return the response
RestClient.get('http://example.com/resource'){|response, request, result| response }

请参阅文档中的“结果处理”部分。

于 2013-02-22T15:50:41.440 回答
4
rescue RestClient::ExceptionWithResponse => err
于 2016-08-10T13:18:34.663 回答
1

可能会发生几个错误,特定的异常类型,如Errno::EHOSTUNREACH或更通用的 ExceptionWithResponse。查看自述文件以获取更多信息。

于 2018-08-31T20:26:29.790 回答
-1

处理休息客户端异常的好方法。

有关更多信息,请检查rest-client#response-callbacks-error-handling

RestClient.get('http://example.com/resource') { |response, request, result, &block|
  case response.code
  when 200
    p "It worked !"
    response
  when 423
    raise SomeCustomExceptionIfYouWant
  else
    response.return!(&block)
  end
}
于 2021-04-29T02:39:56.420 回答