在开始救援中包裹所有控制器操作以进行错误记录

时间:2015-09-07 20:56:20

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

我最近为我的rails应用设置了Rollbar。它报告错误但不总是报告上下文。为了获取上下文,您需要捕获异常并传入错误

begin
  # code...
rescue => e
  Rollbar.error(e)

是否有通过上下文一般性地捕获异常的rails方式?

也许你用一些东西包装应用程序控制器?在Django中,您可以对视图进行子类化...

1 个答案:

答案 0 :(得分:6)

假设所有控制器都继承自ApplicationController,您可以在ApplicationController中使用rescue_from来挽救任何控制器中的任何错误。

ApplicationController < ActionController::Base

  rescue_from ActiveRecord::RecordNotFound do |exception|
    message = "Couldn't find a record."
    redirect_to no_record_url, info: message
  end

end

对于不同的错误类,您可以有多个rescue_from子句,但请注意它们以相反的顺序调用,因此应在其他错误类之前列出通用rescue_from ...

ApplicationController < ActionController::Base

  rescue_from do |exception|
    message = "some unspecified error"
    redirect_to rescue_message_url, info: message
  end

  rescue_from ActiveRecord::RecordNotFound do |exception|
    message = "Couldn't find a record."
    redirect_to rescue_message_url, info: message
  end

end