【问题标题】:How to check for specific rescue clause for error handling in Rails 3.x?如何检查 Rails 3.x 中错误处理的特定救援子句?
【发布时间】:2011-11-29 21:34:34
【问题描述】:

我有以下代码:

begin
  site = RedirectFollower.new(url).resolve
rescue => e
  puts e.to_s
  return false
end

这会引发如下错误:

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。

【问题讨论】:

    标签: ruby-on-rails ruby ruby-on-rails-3 ruby-on-rails-3.1


    【解决方案1】:

    这取决于。

    我看到三个异常描述是不同的。异常类型也不同吗?

    如果是这样,您可以这样编写代码:

    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
    

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

    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
    

    这有帮助吗?

    【讨论】:

      【解决方案2】:

      在“方案 http 不接受注册表部分”的情况下检查什么是异常类(您可以通过 puts e.class 执行此操作)。我认为这将不是“操作超时 - 连接(2)”

      然后:

      begin
        .
      rescue YourExceptionClass => e
        .
      rescue => e
        .
      end
      

      【讨论】:

        【解决方案3】:

        重要提示:使用通配符进行救援,默认为 StandardError。它不会挽救每一个错误。

        例如,SignalException: SIGTERM 不会被 rescue => error 解救。您必须专门使用rescue SignalException => e。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2019-01-11
          • 1970-01-01
          • 1970-01-01
          • 2011-11-08
          • 2014-02-27
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多