简体   繁体   English

Ruby on Rails错误处理,捕获错误和消息

[英]Ruby on Rails Error Handling, Catching Error and Message

I'm trying to figure out the best way to catch a specific error thrown AND the error's message in Ruby on Rails. 我正在尝试找出捕获特定错误并在Ruby on Rails中显示错误消息的最佳方法。 My use case is that I encounter a timeout error every now and then which is thrown with a general error and I want to treat the timeout error differently than other errors within the same general error. 我的用例是,我时不时遇到超时错误,并引发一般错误,并且我希望与同一一般错误中的其他错误区别对待。 I'm not sure what other type of errors could be thrown in the general error but I assume more of them exist. 我不确定一般错误中还会引发什么其他类型的错误,但我认为它们中还有更多错误。 I have some sample code below of how I'm currently handling it, but I was thinking there might be a better way which I haven't found yet? 我下面有一些示例代码说明了我目前的处理方式,但是我认为可能还有一种更好的方法呢?

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

You can use multi rescue , to handle different errors. 您可以使用多重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

Read more: http://phrogz.net/programmingruby/tut_exceptions.html 了解更多: http : //phrogz.net/programmingruby/tut_exceptions.html

You can try Rollbar , it help report error on production. 您可以尝试Rollbar ,它有助于报告生产错误。

Take a look at retriable gem . 看一看可回收的宝石 It seems like a good fit for what you're proposing. 这似乎很适合您的建议。 Usually you'd rescue from an specific error type, but retriable also gives you the choice to rescue based on the error message. 通常,您可以从特定的错误类型中进行救援,但是可重试也可以让您根据错误消息进行救援。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM