【问题标题】:Ruby on Rails Error Handling, Catching Error and MessageRuby on Rails 错误处理、捕获错误和消息
【发布时间】:2025-12-04 21:50:01
【问题描述】:

我正在尝试找出在 Ruby on Rails 中捕获特定错误和错误消息的最佳方法。我的用例是我时不时遇到一个超时错误,该错误会引发一般错误,我希望将超时错误与相同一般错误中的其他错误区别对待。我不确定一般错误中可能会引发哪些其他类型的错误,但我认为存在更多错误。我在下面有一些示例代码说明我目前的处理方式,但我想可能有更好的方法我还没有找到?

tries = 0
begin
  tries += 1
  <code>
rescue Foo::Bar => e
  case e.to_s
  when 'More specific timeout error message'
    retry unless tries >= 5
  else
    # Let me see other error messages
    log.info("Error: #{e.to_s}")
  end
end

【问题讨论】:

  • 您确定超时是使用通用异常类而不是其自己的类引发的,例如 Timeout::Error?
  • 是的,所以错误来自一个外部库,它不时超时,并返回外部库一般错误和超时消息。

标签: ruby-on-rails ruby error-handling rescue


【解决方案1】:

您可以使用多个rescue,来处理不同的错误。

begin
  # DO SOMETHING
rescue Net::Timeout => e # change it to the error your want to catch, check the log.
  # handle it
rescue SyntaxError => e # just an example 
  # handle it
rescue => e # any error that not catch by above rescue go here.
  # handle it
end

阅读更多: http://phrogz.net/programmingruby/tut_exceptions.html

你可以试试Rollbar,它有助于在生产中报告错误。

【讨论】:

    【解决方案2】:

    看看retriable gem。这似乎很适合您的提议。通常你会从特定的错误类型中救援,但 retriable 也让你可以根据错误消息选择救援。

    begin
      Retriable.retriable on: { Foo::Bar => /More specific timeout error message/ }, tries: 3 do
        # will retry if an error of type Foo::Bar is raised
        # and its message matches /More specific timeout error message/
    
        # code here... 
      end
    rescue => e # rescue for everything else
      puts e.message # same as e.to_s
    end
    

    【讨论】: