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

时间:2015-12-28 16:22:02

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

我试图找出捕获特定错误的最佳方法以及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

2 个答案:

答案 0 :(得分:4)

您可以使用多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,它有助于报告生产错误。

答案 1 :(得分:0)

看看retriable gem。它似乎非常适合你提出的建议。通常你会从特定的错误类型中解救出来,但是可以根据错误信息让你可以选择进行救援。

angular.module ( 'myApp' )
.controller (
'ProtectedCtrl', function ($localStorage, $scope)
{
    var myImage = [];

    $localStorage.myImage = document.getElementById('image-handle');
    console.log($localStorage.myImage);
});