rescue_from无法在ActiveJob

时间:2017-07-04 07:50:20

标签: ruby-on-rails

我的课程:

class TestUpdateJob < ActiveJob::Base

  include ActiveSupport::Rescuable
  rescue_from UserMediaException::UserNotFound, with: :destroy_user

  def self.call
    um = UserMedia.call('81274092340912873',100)
  end

  def destroy_user
    print "User to be destroyed"
  end


end

UserMedia.call('81274092340912873',100)引发UserMediaException::UserNotFound例外。

我试图测试rescue_from,但我无法使其正常运行。消息&#34;要销毁的用户&#34;永远不会被打印出来。

我正在执行的自定义异常(UserMediaException::UserNotFound)继承自StandardError。

知道为什么会这样吗?

1 个答案:

答案 0 :(得分:1)

根据ActiveJobs文档,所有作业类必须在perform实例方法中具有其业务逻辑。

您的代码应为:

class TestUpdateJob < ActiveJob::Base

  include ActiveSupport::Rescuable
  rescue_from UserMediaException::UserNotFound, with: :destroy_user

  def perform
    um = UserMedia.call('81274092340912873',100)
  end

  private

  def destroy_user
    print "User to be destroyed"
  end

end

您可以使用perform_later的作业将其排入队列,或perform_now直接执行该作业:

TestUpdateJob.perform_later # Enqueue your job and execute it asynchronously
TestUpdateJob.perform_now # Execute your job now