Rails:救援类继承

问题描述 投票:2回答:3

我有一份有run方法的工作,看起来像这样:

def perform(share, document)
  @history = document.scheduled_posts.find_by(provider: share[:provider])
  job = ProviderJob.new(document, share)
  begin
    job.run
    @history.update_columns(response: 'posted', status: 'complete')
  rescue StandardError => e
    @history.update_columns(response: e.message, status: 'error')
    raise Errors::FailedJob, e.message
  rescue FbGraph2::Exception::Unauthorized, Twitter::Error::Unauthorized, Mailchimp::UserUnknownError, LinkedIn::OAuthError, Errors::MissingAuth => e
    @history.update_columns(response: e.message, status: 'unauthorised')
    raise Errors::FailedJob, e.message
  end
end

即使Errors::MissingAuth被提升,StandardError块也会抓住它,因为它继承了它。如何确保正确的块捕获指定的异常?

ruby-on-rails ruby ruby-on-rails-5
3个回答
3
投票

这些救援块按顺序执行。你应该先把更具体的一些。移动那个StandardError最后一个。


2
投票

救援区按顺序运行。因为Errors :: MissingAuth继承自StandardError,所以StandardError块将始终首先触发。您应该更改救援块的优先级,例如:

def perform(share, document)
  @history = document.scheduled_posts.find_by(provider: share[:provider])
  job = ProviderJob.new(document, share)
  begin
    job.run
    @history.update_columns(response: 'posted', status: 'complete')
  rescue FbGraph2::Exception::Unauthorized, Twitter::Error::Unauthorized, Mailchimp::UserUnknownError, LinkedIn::OAuthError, Errors::MissingAuth => e
    @history.update_columns(response: e.message, status: 'unauthorised')
    raise Errors::FailedJob, e.message
  rescue StandardError => e
    @history.update_columns(response: e.message, status: 'error')
    raise Errors::FailedJob, e.message
  end
end

2
投票

如果其他答案有效,我认为这是一种更好的方法。我没有意识到这一点,并开始输入另一个答案,所以无论如何我都会包含它。

我假设这里的所有错误都继承自StandardError。在这种情况下,您可以使用单个救援,并根据引发的错误的类配置行为:

rescue StandardError => e
  status = [
    FbGraph2::Exception::Unauthorized, Twitter::Error::Unauthorized,
    Mailchimp::UserUnknownError, LinkedIn::OAuthError, Errors::MissingAuth
  ].include?(e.class) ? 'unauthorized' : 'error'
  @history.update_columns(response: e.message, status: status)
  raise Errors::FailedJob, e.message
end
© www.soinside.com 2019 - 2024. All rights reserved.