Rails:救援类继承

时间:2018-03-04 23:52:42

标签: ruby-on-rails ruby ruby-on-rails-5

我的工作有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::MissingAuthStandardError块也会捕获它,因为它继承了它。如何确保正确的块捕获指定的异常?

3 个答案:

答案 0 :(得分:3)

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

答案 1 :(得分: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 :(得分: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
相关问题