如何从Ruby的Net :: HTTP中的读取超时错误中判断连接超时错误

我的问题与 How to rescue timeout issues (Ruby,Rails)有关.

以下是从超时中解救的常用方法

def action
  # Post using Net::HTTP
rescue Timeout::Error => e
  # Do something
end

我想确定在尝试连接到主机时是否引发了异常,或者在尝试从主机读取时是否引发了异常.这可能吗?

解决方法

这是解决方案(在Ben的修复之后):
require "net/http"
http = Net::HTTP.new("example.com")
http.open_timeout = 2
http.read_timeout = 3
begin
  http.start
  begin
    http.request_get("/whatever?") do |res|
      res.read_body
    end
  rescue Timeout::Error
    puts "Timeout due to reading"
  end
rescue Timeout::Error
  puts "Timeout due to connecting"
end

相关文章

validates:conclusion,:presence=>true,:inclusion=>{...
一、redis集群搭建redis3.0以前,提供了Sentinel工具来监控各...
分享一下我老师大神的人工智能教程。零基础!通俗易懂!风趣...
上一篇博文 ruby传参之引用类型 里边定义了一个方法名 mo...
一编程与编程语言 什么是编程语言? 能够被计算机所识别的表...
Ruby类和对象Ruby是一种完美的面向对象编程语言。面向对象编...