如何让ExceptionNotifier在Rails 3中与delayed_job一起使用?

Ale*_*ban 25 delayed-job ruby-on-rails-3 exception-notification

我希望ExceptionNotifier在延迟作业中发生异常时发送电子邮件,就像其他异常一样.我怎样才能做到这一点?

Mat*_*man 23

我使用Rails 3.2.6,delayed_job 3.0.3和exception_notification 2.6.1 gem来做到这一点

# In config/environments/production.rb or config/initializers/delayed_job.rb

# Optional but recommended for less future surprises.
# Fail at startup if method does not exist instead of later in a background job 
[[ExceptionNotifier::Notifier, :background_exception_notification]].each do |object, method_name|
  raise NoMethodError, "undefined method `#{method_name}' for #{object.inspect}" unless object.respond_to?(method_name, true)
end

# Chain delayed job's handle_failed_job method to do exception notification
Delayed::Worker.class_eval do 
  def handle_failed_job_with_notification(job, error)
    handle_failed_job_without_notification(job, error)
    # only actually send mail in production
    if Rails.env.production?
      # rescue if ExceptionNotifier fails for some reason
      begin
        ExceptionNotifier::Notifier.background_exception_notification(error)
      rescue Exception => e
        Rails.logger.error "ExceptionNotifier failed: #{e.class.name}: #{e.message}"
        e.backtrace.each do |f|
          Rails.logger.error "  #{f}"
        end
        Rails.logger.flush
      end
    end
  end 
  alias_method_chain :handle_failed_job, :notification 
end
Run Code Online (Sandbox Code Playgroud)

在所有环境中加载此代码以在捆绑更新之后捕获错误(在它们到达生产之前)可能是个好主意.我这样做是通过提供一个config/initializers/delayed_job.rb文件但你可以复制每个config/environments/*环境的代码.

另一个提示是将延迟的作业配置调整为默认值,当作业失败时,您可能会收到大量重复的异常邮件.

# In config/initializers/delayed_job_config.rb
Delayed::Worker.max_attempts = 3
Run Code Online (Sandbox Code Playgroud)

更新我有一些问题,delayed_job守护进程默默地退出,结果发现ExceptionNotifier无法发送邮件,没有人救出异常.现在代码拯救并记录它们.

  • 我在方法调用中添加了一个```,:data => {:job => job}```,这样我就可以获得更多细节...... (3认同)

Alt*_*gos 5

添加到@MattiasWadman答案,因为exception_notification 4.0 有一种处理手动通知的新方法.所以代替:

ExceptionNotifier::Notifier.background_exception_notification(error)
Run Code Online (Sandbox Code Playgroud)

使用

ExceptionNotifier.notify_exception(error)
Run Code Online (Sandbox Code Playgroud)