首页 > 解决方案 > Sidekiq 作业错误处理并在父作业中重试?

问题描述

我有一个工作,它会产生其他工作并且内联做一些事情。

abc_job.rb

class AbcJob
  def perform
    post_events
  end

  private

  def post_events
    foo
    bar
    done
  end

  def foo
    OneJob.perform_later({})
  end

  def bar
    TwoJob.perform_later({})
  end

  def done
    ThreeJob.perform_later({})
  end
end

需要处理错误并为里面的所有作业添加重试abc_job

一种方法是在post_events所有方法中添加开始救援。

请建议最好的方法,并且还需要为子作业添加重试。

标签: ruby-on-railsrubyjobssidekiq

解决方案


您可以做的一种方法是使用元编程。您可以创建一个外部模块说ExceptionHandler->您可以rescue在这里处理错误时处理错误->然后将此模块包含在您的AbcJob文件中。

前任:

  1. 创建一个模块文件:

    module ExceptionHandler
      extend ActiveSupport::Concern
    
      # Define custom error subclasses - rescue catches `StandardErrors`
      class InvalidToken < StandardError; end
      class MissingToken < StandardError; end
    
      included do
        # Define in-built handlers
        rescue_from ActiveRecord::RecordNotFound, with: :four_not_four
        rescue_from ActiveRecord::RecordInvalid, with: :four_not_four
    
        # Define custom handlers
        rescue_from ExceptionHandler::MissingToken, with: :unauthorized_request
        rescue_from ExceptionHandler::InvalidToken, with: :unauthorized_request
      end
    
      private
        ## Action on what to do when error occurs
        def four_not_four
          redirect_to root_path, alert: "This page was not found"
        end
    
        def unauthorized_request
          redirect_to root_path, alert: "You're not authorized to perform this request"
        end
    end
    
  2. 然后在您的Abcjob文件中,只需包含此模块:

    class AbcJob
      include ExceptionHandler
    
      def perform
        post_events
      end
    
      ...
    end
    
  3. 现在,每当作业抛出处理程序时,这将触发您在中提到的方法ExceptionHandler并运行它们。


推荐阅读