所以,我有以下代码( connection.rb ):
require 'net/http'
require 'net/https'
require 'openssl'
class Connection
def request
body = '<?xml version="1.0" encoding="UTF-8"?>...'
path = '/path'
http = Net::HTTP.new('192.168.12.34', '1234')
http.read_timeout = 60
p "=1"
http.request_post(path, body, {'Content-Type' => 'application/xml'})
p "=2"
...
rescue Net::ReadTimeout => ex
...
end
end
在字符串 http.request_post(...)中,我得到输出:
"=1"
NameError: uninitialized constant Net::ReadTimeout
/home/user/invp/lib/connection.rb:76:in `rescue in request'
/home/user/invp/lib/connection.rb:26:in `request'
/home/user/invp/lib/tasks/task.rake:225:in `block (2 levels) in <top (required)>'
我的环境:
user@vm-dev:~/invp$ ruby --version
ruby 1.9.3p484 (2013-11-22 revision 43786) [x86_64-linux]
user@vm-dev:~/invp$ rails --version
Rails 3.2.12
怎么了?
答案 0 :(得分:3)
对于 ruby 1.9.3 ,会引发 TimeoutError 异常。
对于 ruby 2.3.1 ,它会引发 Net :: ReadTimeout 异常。
因此,您应该使用rescue TimeoutError
或更新您的ruby版本。
refs(在页面末尾搜索read_timeout):
http://ruby-doc.org/stdlib-1.9.3/libdoc/net/http/rdoc/Net/HTTP.html
http://ruby-doc.org/stdlib-2.3.1/libdoc/net/http/rdoc/Net/HTTP.html
还有一个信息:Net :: ReadTimeout是TimeoutError的子类,似乎是在ruby-2.0.0上添加的: