【问题标题】:Handle exception in ruby on rails处理 ruby​​ on rails 中的异常
【发布时间】:2018-10-26 06:28:03
【问题描述】:

我在工作人员的模型内部调用了一个方法@txt.watch,在watch() 内部有一个parameters(parameters = self.parameters) 数组。每个参数都有唯一的参考 ID。 我想从工作人员内部拯救每个参数的每个异常错误。

 class TextWorker
    def perform(id)
      @txt = WriteTxt.find(id)
      begin
        @txt.watch
        total_complete_watch = if @txt.job_type == 'movie'
                                @txt.total_count
                              else
                                @txt.tracks.where(status:'complete').size
                              end
        @txt.completed = total_completed_games
        @txt.complete = (total_complete_games == @txt.total_count)
        @txt.completed_at = Time.zone.now if @txt.complete
        @txt.zipper if @txt.complete
        @txt.save
        FileUtils.rm_rf @txt.base_dir if @txt.complete
      rescue StandardError => e
        #How to find errors for each reference_id here
      raise e
      end
    end
  end

有什么办法吗。非常感谢你。

【问题讨论】:

  • 异常一一提出,不收集。
  • 如果@txt.watch 在任何阶段抛出错误,您的代码将跳转到调用rescue StandardError => e 行。你能分享watch的方法吗?最好在里面做这个。
  • def watch txt = '' self.parameters.each do |parameter| txt += movie_list(参数) end write_list(txt) end

标签: ruby-on-rails ruby exception


【解决方案1】:

我假设self.parameters 在您的 Model 类实例中。在这种情况下,请执行以下操作,您可以参考它们。

begin
  @txt.watch
rescue StandardError
  p @parameters  # => self.parameters in the Model context
  raise
end

注意

根据经验,建议尽可能缩小救援范围。不要在主子句中包含不应引发异常的语句(例如,@txt.saveFileUtils.rm_rf 在您的情况下)。此外,最好限制异常的类别;例如,救援Encoding::CompatibilityError 代替EncodingError,或EncodingError 代替StandardError,等等。或者,更好的方法是定义您自己的 Exception 类并故意引发它。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多