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

use*_*587 2 error-handling ruby-on-rails rollbar

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

begin
  # code...
rescue => e
  Rollbar.error(e)
Run Code Online (Sandbox Code Playgroud)

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

也许你用应用程序控制器包装?在Django中,您可以继承视图...

Ste*_*zyn 6

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

ApplicationController < ActionController::Base

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

end
Run Code Online (Sandbox Code Playgroud)

您可以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
Run Code Online (Sandbox Code Playgroud)