6

当对方法的调用如下所示时,谁能解释为什么我可能会看到这个堆栈(由 HTTParty::post 请求引起):

begin
  response = HTTParty::post(url, options)
rescue
  logger.warn("Could not post to #{url}")      
rescue Timeout::Error
  logger.warn("Could not post to #{url}: timeout")      
end

堆栈:

/usr/local/lib/ruby/1.8/timeout.rb:64:in `timeout'
/usr/local/lib/ruby/1.8/net/protocol.rb:134:in `rbuf_fill'
/usr/local/lib/ruby/1.8/net/protocol.rb:104:in `read_all'
/usr/local/lib/ruby/1.8/net/http.rb:2228:in `read_body_0'
/usr/local/lib/ruby/1.8/net/http.rb:2181:in `read_body'
/usr/local/lib/ruby/1.8/net/http.rb:2206:in `body'
/usr/local/lib/ruby/1.8/net/http.rb:2145:in `reading_body'
/usr/local/lib/ruby/1.8/net/http.rb:1053:in `request_without_newrelic_trace'
[GEM_ROOT]/gems/newrelic_rpm-3.1.1/lib/new_relic/agent/instrumentation/net.rb:20:in `request'
[GEM_ROOT]/gems/newrelic_rpm-3.1.1/lib/new_relic/agent/method_tracer.rb:242:in `trace_execution_scoped'
[GEM_ROOT]/gems/newrelic_rpm-3.1.1/lib/new_relic/agent/instrumentation/net.rb:19:in `request'
/usr/local/lib/ruby/1.8/net/http.rb:1037:in `request_without_newrelic_trace'
/usr/local/lib/ruby/1.8/net/http.rb:543:in `start'
/usr/local/lib/ruby/1.8/net/http.rb:1035:in `request_without_newrelic_trace'
[GEM_ROOT]/gems/newrelic_rpm-3.1.1/lib/new_relic/agent/instrumentation/net.rb:20:in `request'
[GEM_ROOT]/gems/newrelic_rpm-3.1.1/lib/new_relic/agent/method_tracer.rb:242:in `trace_execution_scoped'
[GEM_ROOT]/gems/newrelic_rpm-3.1.1/lib/new_relic/agent/instrumentation/net.rb:19:in `request'
[GEM_ROOT]/gems/httparty-0.7.8/lib/httparty/request.rb:69:in `perform'
[GEM_ROOT]/gems/httparty-0.7.8/lib/httparty.rb:390:in `perform_request'
[GEM_ROOT]/gems/httparty-0.7.8/lib/httparty.rb:358:in `post'
[GEM_ROOT]/gems/httparty-0.7.8/lib/httparty.rb:426:in `post'

如您所见,我正在处理 Timeout::Error 异常。这是在 Ruby 1.8.7 中。我很清楚在 Ruby 1.8.7 中,StandardException 和 TimeoutException 有不同的继承树,所以我处理了这两个,但似乎没有什么区别。

4

1 回答 1

4

当您省略 中的异常类时rescue,它将捕获任何StandardError. 由于Timeout::Error是 的子类StandardError,它将被第一个rescue语句捕获。如果要单独捕获它,则必须将其放在省略的之前:

begin
  response = HTTParty::post(url, options)
rescue Timeout::Error
  logger.warn("Could not post to #{url}: timeout")      
rescue
  logger.warn("Could not post to #{url}")      
end
于 2012-03-20T05:46:52.817 回答