Net::HTTP vs REST Client gem:他们如何处理不良网站/404

Net::HTTP vs REST Client gem: How do they handle bad websites / 404

我试图使用 rest-client gem 访问一些网站,但我发现了一个令我困惑的行为。它与在不良网站上使用 rest-client 有关,在本例中为 www.google.com/this_does_not_exist。

我的预期:代码将 运行 并且响应对象将具有 404 响应代码。

实际情况:出现异常,代码提前终止。

当我用 Net::HTTP 库尝试同样的事情时,我确实得到了预期的结果。

问题是:这种行为在 rest-client 中是预期的吗?如果是这样,当使用不良网站时,您将如何取回带有 404 响应代码的对象。

这是我的 irb 的代码:

2.2.1 :045 > uri = URI('http://www.google.com')
 => #<URI::HTTP http://www.google.com> 
2.2.1 :046 > response = Net::HTTP.get_response(uri)
 => #<Net::HTTPOK 200 OK readbody=true> 
2.2.1 :047 > response.code
 => "200" 
2.2.1 :048 > uri = URI('http://www.google.com/this_does_not_exist')
 => #<URI::HTTP http://www.google.com/this_does_not_exist> 
2.2.1 :049 > response = Net::HTTP.get_response(uri)
 => #<Net::HTTPNotFound 404 Not Found readbody=true> 
2.2.1 :050 > response.code
 => "404" 
2.2.1 :051 > uri = URI('http://www.google.com')
 => #<URI::HTTP http://www.google.com> 
2.2.1 :052 > response = RestClient.get('http://www.google.com')
 => <RestClient::Response 200 "<!doctype h..."> 
2.2.1 :053 > response.code
 => 200 
2.2.1 :054 > response = RestClient.get('http://www.google.com/this_does_not_exist')
RestClient::NotFound: 404 Not Found
    from /Users/piperwarrior/.rvm/gems/ruby-2.2.1/gems/rest-client-2.0.0/lib/restclient/abstract_response.rb:223:in `exception_with_response'
    from /Users/piperwarrior/.rvm/gems/ruby-2.2.1/gems/rest-client-2.0.0/lib/restclient/abstract_response.rb:103:in `return!'
    from /Users/piperwarrior/.rvm/gems/ruby-2.2.1/gems/rest-client-2.0.0/lib/restclient/request.rb:860:in `process_result'
    from /Users/piperwarrior/.rvm/gems/ruby-2.2.1/gems/rest-client-2.0.0/lib/restclient/request.rb:776:in `block in transmit'
    from /Users/piperwarrior/.rvm/rubies/ruby-2.2.1/lib/ruby/2.2.0/net/http.rb:853:in `start'
    from /Users/piperwarrior/.rvm/gems/ruby-2.2.1/gems/rest-client-2.0.0/lib/restclient/request.rb:766:in `transmit'
    from /Users/piperwarrior/.rvm/gems/ruby-2.2.1/gems/rest-client-2.0.0/lib/restclient/request.rb:215:in `execute'
    from /Users/piperwarrior/.rvm/gems/ruby-2.2.1/gems/rest-client-2.0.0/lib/restclient/request.rb:52:in `execute'
    from /Users/piperwarrior/.rvm/gems/ruby-2.2.1/gems/rest-client-2.0.0/lib/restclient.rb:67:in `get'
    from (irb):54
    from /Users/piperwarrior/.rvm/rubies/ruby-2.2.1/bin/irb:11:in `<main>'
2.2.1 :055 > 

来自GitHub README

  • 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

所以是的,这是预期的行为,可以使用 e.response 检索响应对象。