How to handle exceptions with Ruby Rest-Client

匿名 (未验证) 提交于 2019-12-03 02:47:02

问题:

I recently switched from Ruby's Net:HTTP class to rest-client 1.6.7.

I find it a lot easier to form requests, but unlike Net:HTTP request, when rest-client gets anything other than a 200, the request dies. I've tried putting a breakpoint directly after the RestClient.get, and it never gets hit - so I'm doing something wrong.

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

Which results in this stacktrace:

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'

Can someone tell me how to properly evaluate the response code and keep this exception from happening...?

回答1:

See heading Exceptions on http://rubydoc.info/gems/rest-client/

  • for results code between 200 and 207 a RestClient::Response will be returned
  • for results code 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 know error codes



回答2:

Also in the same documentation @wich pointed to, you can pass a block to RestClient.get such that it will not throw an exception on non-200 response codes:

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

See the "Result Handling" section: http://www.rubydoc.info/gems/rest-client/1.6.7/frames#Result_handling



回答3:

rescue RestClient::ExceptionWithResponse => err


易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!