我的问题与
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