【问题标题】:Rails: rescue class inheritanceRails:救援类继承
【发布时间】:2018-08-12 14:15:33
【问题描述】:

我有一份工作,其 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


    【解决方案1】:

    这些救援块按顺序执行。你应该把更具体的放在第一位。将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
    

    【讨论】:

      【解决方案3】:

      如果其他答案有效,我认为这是一种更好的方法。我没有意识到这一点,并开始输入另一个答案,所以我还是把它包括在内。

      我假设这里的所有错误都继承自 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
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2023-01-13
        • 1970-01-01
        • 1970-01-01
        • 2012-02-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-10-24
        相关资源
        最近更新 更多