Ruby 错误处理 : Rescuing Exceptions in Subclasses

标签 ruby inheritance error-handling custom-error-handling airbrake

我有一组连接到各种 API 的 Adapter 类,等等。以下是每个适配器如何设置的简单通用示例:

class AmazonAdapter
    include Sidekiq::Worker
    def perform(id)
        get_results_from_api(id)
    end
end

class WalmartAdapter
    include Sidekiq::Worker
    def perform(id)
        get_results_from_api(id)
    end
end

所以一般来说,通过调用 AmazonAdapter.new(500) ,它将连接到 API 并根据您作为 ID 传入的内容返回结果。这都是 Sidekiq 收集过程的一部分,并作为后台作业运行,因此当出现问题时它不一定会抛出明显的异常或错误来提醒我。

当 API 未正确连接或抛出任何其他错误时,我想使用 AirBrake 的通知系统通知我,但不会停止收集过程或 sidekiq。我希望将错误处理和通知系统纳入主流。

我的一些想法是创建一个子类可以从中继承的 ParentClass,看起来类似于:
class Adapter
    include Sidekiq::Worker
    def perform(id)
        begin
            #execute subclass perform method
        rescue Exception => e
            Airbrake.notify(e)
        end
    end
end

但我不太确定解决这个问题的最佳方法。我真的可以在这方面使用一些建议或帮助,谢谢!

最佳答案

Sidekiq 中存在瓶颈基本上执行一切: Sidekiq::Processor#execute_job ,接收两个参数 (worker, cloned_args)随后调用 worker.perform(*cloned_args) .因此,出于您的目的,我将在模块前添加:

Sidekiq::Processor.prepend(Module.new do
  def execute_job(worker, cloned_args)
    super # CALL ORIGINAL
  rescue => e # NEVER RESCUE FROM EXCEPTION!!!
    Airbrake.notify(e) # NOTIFY
    raise e # RE-RAISE SO SIDEKIQ DOES HIS JOB
  end
end)

在你的第一份工作之前调用它,你就完成了:在 Sidekiq 调用工作人员期间发生的所有错误现在都被空气制动了。

希望能帮助到你。

关于Ruby 错误处理 : Rescuing Exceptions in Subclasses,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39621603/

相关文章:

MS-Access VBA : form_error vs on error

Ruby 正则表达式太大/多个字符串匹配

c++ - 如何在C++中继承类?

c# - WPF MVVM 应用程序中多个异步调用期间的单个错误弹出

python - 继承、Python 和 wxWidget

swift - 如何使父类(super class)中的方法创建子类对象?

error-handling - 错误: listen EADDRINUSE: address already in use:::3000 … I got this error please tell me the solution this

ruby-on-rails - 将数组缩放到最小值/最大值

ruby - 如何删除数组中的空字符串

ruby - 安装时的 Eventmachine 问题(安装 Middleman 时)