2

I want to be able to define the exception_recipients dynamically, based on the Rails environment. For example:

recipients = Rails.env == 'production'
   exceptions@myapp.com
else
   User.current.email
end

However, from the docs:

Whatever::Application.config.middleware.use ExceptionNotification::Rack,
  :email => {
    :email_prefix => "[Whatever] ",
    :sender_address => %{"notifier" <notifier@example.com>},
    :exception_recipients => %w{exceptions@example.com}
  }

In config/environments/production.rb where i don't have an ActiveRecord::Base connection yet.

How can I set the exceptions recipients after Rails has loaded?

Thanks

4

2 回答 2

1

自定义通知程序

您可以创建一个继承自 的自定义通知程序,EmailNotifier它将User.current.email在非生产环境中使用。

# app/models/exception_notifier/custom_notifier.rb
#
module ExceptionNotifier
  class CustomNotifier < EmailNotifier

    def initialize(options)
      @fallback_exception_recipients = options[:fallback_exception_recipients]
      options[:exception_recipients] ||= options[:fallback_exception_recipients]
      super(options)
    end

    def call(exception, options = {})
      options[:exception_recipients] = [User.current.email] unless Rails.env.production?
      super(exception, options)
    end

  end
end

初始化器

例如,回退地址可以从初始化程序传递。

# config/initializers/exception_notification.rb
#
Rails.application.config.middleware.use ExceptionNotification::Rack, {
  :custom => {
    :fallback_exception_recipients => %w{exceptions@myapp.com},
    # ...
  }
}

current_user代替User.current

我不确定你的User.current电话是否可以在这里工作。但是,您将 传递current_user给异常数据,如README中所示。

# app/controllers/application_controller.rb
#
class ApplicationController < ActionController::Base
  before_filter :prepare_exception_notifier
  private
  def prepare_exception_notifier
    request.env["exception_notifier.exception_data"] = {
      :current_user => current_user
    }
  end
end

然后,ExceptionNotifier::CustomNotifier#call用这个替换上面的方法:

# app/models/exception_notifier/custom_notifier.rb
#
module ExceptionNotifier
  class CustomNotifier < EmailNotifier

    # ...

    def call(exception, options = {})
      unless Rails.env.production?
        if current_user = options[:env]['exception_notifier.exception_data'][:current_user]
          options[:exception_recipients] = [current_user.email]
        end
      end
      super(exception, options)
    end

  end
end
于 2016-06-16T13:26:58.923 回答
0

开箱即用不支持此功能。您可以按照文档中的说明创建自己的自定义通知程序:https ://github.com/smartinez87/exception_notification#custom-notifier

您可以查看内置EmailNotifier并可能对其进行扩展,然后只需覆盖initializeorcompose_email方法以使其满足您的需要。

https://github.com/smartinez87/exception_notification/blob/master/lib/exception_notifier/email_notifier.rb#L120

https://github.com/smartinez87/exception_notification/blob/master/lib/exception_notifier/email_notifier.rb#L90

于 2013-10-12T02:27:59.597 回答