微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何从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

原文地址:https://www.jb51.cc/ruby/268614.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐