为了避免 ActionMailer 无法 rescue 的问题,我们可以手动设置 perform 方法,并将其指向 rescue_with_handler 方法,以确保出现任何异常时都能被 rescue。
class MyMailer < ApplicationMailer
include Sidekiq::Worker
sidekiq_options retry: 5
def send_email(user)
mail(to: user.email, subject: "邮件主题")
end
def self.perform(*args)
begin
super(*args)
rescue => ex
rescue_with_handler(ex) || raise(ex)
end
end
def self.rescue_with_handler(ex)
# 处理异常
end
end
在上面的示例代码中,我们通过 include Sidekiq::Worker 将 MyMailer 转为 Sidekiq 可执行的 Worker,并使用 sidekiq_options 指定了重试次数。
同时,我们手动指定了 perform 方法,并在其中使用 rescue_with_handler 方法处理异常,以确保无论何时调用 MyMailer 类时都能 rescue。这样,我们就可以避免 ActionMailer 在被调用时出现异常时无法 rescue 的问题。