处理延迟作业的错误

时间:2011-11-22 15:17:42

标签: ruby-on-rails delayed-job

是否有可能使用delayed_job gem处理错误?我想找到一种方法(运行时)在发生错误时以及在执行删除后将电子邮件发送到给定帐户。

3 个答案:

答案 0 :(得分:1)

这是你想要的吗?

def do_something
  # some code here
  begin
    # something that could go wrong here
  rescue Exception => e
    YourMailer.delay.your_method(e.to_s)
    # don't know what you want to delete, but you can do it here
  end
end

答案 1 :(得分:1)

在此处找到解决方案:http://blog.salsify.com/engineering/delayed-jobs-callbacks-and-hooks-in-rails

# config/initizalizers/delayed_job.rb

class ExceptionMailerPlugin < Delayed::Plugin

  callbacks do |lifecycle|
    lifecycle.around(:invoke_job) do |job, *args, &block|
      begin
        # Forward the call to the next callback in the callback chain
        block.call(job, *args)
      rescue Exception => error
        ErrorMailer.exception_mail(error)
        # Make sure we propagate the failure!
        raise error
      end
    end
  end

end


Delayed::Worker.plugins << ExceptionMailerPlugin

答案 2 :(得分:0)

不是上面的代码并没有报告所有问题。.最近我们在工人测功机上遇到了很多问题,我们甚至没有意识到它们,因为我们仅在侦听错误...

DelayedJob知道两种错误类型-错误和失败。在我们的案例中-由于使用的是章鱼宝石,因此失败是在较低级别上触发的。失败消息为:undefined method []'for nil:NilClass`

class DelayedJobExceptionPlugin < Delayed::Plugin
  def self.report_error(exception, job, type: 'error')
    Airbrake.notify(
      exception, 
      error_message: "#{exception.class.name}: #{exception.message}",
      backtrace: exception.backtrace,
      component: 'DelayedJob Worker',
      type: type,
      parameters: {
        failed_job: job.inspect
      },
    )
  end

  callbacks do |lifecycle|
    lifecycle.around(:invoke_job) do |job, *args, &block|
      begin
        # Forward the call to the next callback in the callback chain
        block.call(job, *args)
      rescue Exception => exception
        DelayedJobExceptionPlugin.report_error(exception, job)

        raise error
      end
    end

    lifecycle.after(:failure) do |job| # Note - some jobs did not trigger Airbrake.notify if we do not use failure!
      exception = ::RuntimeError.new('DelayedJob Failure')
      DelayedJobExceptionPlugin.report_error(exception, job, type: 'failure')

      raise exception if Rails.env.test?
    end
  end
end

Delayed::Worker.plugins << DelayedJobExceptionPlugin