如何使用Ruby Rest-Client处理异常

时间:2012-07-10 22:38:58

标签: ruby rest-client

我最近从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'

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

5 个答案:

答案 0 :(得分:51)

请参阅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

答案 1 :(得分:21)

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

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

请参阅“结果处理”部分:http://www.rubydoc.info/gems/rest-client/1.6.7/frames#Result_handling

答案 2 :(得分:4)

rescue RestClient::ExceptionWithResponse => err

答案 3 :(得分:0)

可能会发生几种错误,例如 Errno :: EHOSTUNREACH 或更特殊的ExceptionWithResponse之类的特定异常类型。 Check the readme了解更多信息。

答案 4 :(得分:0)

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

有关更多信息,请查看 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
}