如何在Rails 3.x中检查错误处理的特定救援条款?

use*_*097 8 ruby ruby-on-rails ruby-on-rails-3 ruby-on-rails-3.1

我有以下代码:

begin
  site = RedirectFollower.new(url).resolve
rescue => e
  puts e.to_s
  return false
end
Run Code Online (Sandbox Code Playgroud)

这会引发错误:

the scheme http does not accept registry part: www.officedepot.com;

the scheme http does not accept registry part: ww2.google.com/something;

Operation timed out - connect(2)

如何为所有类似的错误添加另一个救援the scheme http does not accept registry part

因为我想做的不仅仅是打印错误并在这种情况下返回false.

leo*_*ges 14

那要看.

我看到三个异常描述是不同的.异常类型是否也有所不同?

如果是这样你就可以这样写你的代码:

begin
  site = RedirectFollower.new(url).resolve
rescue ExceptionType1 => e
  #do something with exception that throws 'scheme http does not...'
else
  #do something with other exceptions
end
Run Code Online (Sandbox Code Playgroud)

如果异常类型相同,那么您仍然会有一个救援块,但会根据正则表达式决定做什么.也许是这样的:

begin
  site = RedirectFollower.new(url).resolve
rescue Exception => e
  if e.message =~ /the scheme http does not accept registry part/
      #do something with it
  end
end
Run Code Online (Sandbox Code Playgroud)

这有帮助吗?


spa*_*ovv 6

在'方案http不接受注册表部分'的情况下检查什么是异常类(你可以这样做puts e.class).我假设这不是'操作超时 - 连接(2)'

然后:

begin
  .
rescue YourExceptionClass => e
  .
rescue => e
  .
end
Run Code Online (Sandbox Code Playgroud)