从Sidekiq作业中获取错误消息

时间:2014-06-18 07:01:15

标签: ruby-on-rails sidekiq

我想从sidekiq作业中获取异常错误消息。当我将back_trace选项设置为true时,它会重试我的作业,但是当错误引发并收到错误消息时我想退出作业。

如果我发现流程结束成功或失败就足够了。

def perform(text)
    begin
      fail StandardError, 'Error!' 
    rescue
      fail 'EEE' # I want to get this error when call job
    end
end
# call
NormalJob.perform_async('test')
# I want to get error here after call

1 个答案:

答案 0 :(得分:4)

如果我是你,我会尝试宝石sidekiq-status。它有几个选项,在这种情况下可能会有所帮助:

您可以检索工作人员的状态

job_id = MyJob.perform_async(*args)
# :queued, :working, :complete or :failed , nil after expiry (30 minutes)
status = Sidekiq::Status::status(job_id)
Sidekiq::Status::queued?   job_id
Sidekiq::Status::working?  job_id
Sidekiq::Status::complete? job_id
Sidekiq::Status::failed?   job_id

您还可以选择Tracking progress, saving and retrieveing data associated with job

class MyJob
  include Sidekiq::Worker
  include Sidekiq::Status::Worker # Important!

  def perform(*args)
    # your code goes here

    # the common idiom to track progress of your task
    total 100 # by default
    at 5, "Almost done"

    # a way to associate data with your job
    store vino: 'veritas'

    # a way of retrieving said data
    # remember that retrieved data is always is String|nil
    vino = retrieve :vino
  end
end

job_id = MyJob.perform_async(*args)
data = Sidekiq::Status::get_all job_id
data # => {status: 'complete', update_time: 1360006573, vino: 'veritas'}
Sidekiq::Status::get     job_id, :vino #=> 'veritas'
Sidekiq::Status::at      job_id #=> 5
Sidekiq::Status::total   job_id #=> 100
Sidekiq::Status::message job_id #=> "Almost done"
Sidekiq::Status::pct_complete job_id #=> 5

另一种选择是使用sidekiq batches status

这是批次允许你做的事情!

batch = Sidekiq::Batch.new
batch.description = "Batch description (this is optional)"
batch.notify(:email, :to => 'me@example.org')
batch.jobs do
  rows.each { |row| RowWorker.perform_async(row) }
end
puts "Just started Batch #{batch.bid}"

b = Sidekiq::Batch.new(bid) # bid is a method on Sidekiq::Worker that gives access to the Batch ID associated to the job.
b.jobs do
  SomeWorker.perform_async(1)
  sleep 1
  # Uh oh, Sidekiq has finished all outstanding batch jobs
  # and fires the complete message!
  SomeWorker.perform_async(2)
end

status = Sidekiq::Batch::Status.new(bid)
status.total # jobs in the batch => 98
status.failures # failed jobs so far => 5
status.pending # jobs which have not succeeded yet => 17
status.created_at # => 2012-09-04 21:15:05 -0700
status.complete? # if all jobs have executed at least once => false
status.join # blocks until the batch is considered complete, note that some jobs might have failed
status.failure_info # an array of failed jobs
status.data # a hash of data about the batch which can easily be converted to JSON for javascript usage

它可以直接使用