Bablu Patel
Bablu Patel

Reputation: 85

Handle exception in ruby on rails

I called a method @txt.watch inside model from worker and Inside watch() there is an array of parameters(parameters = self.parameters). Each parameter have unique reference id. I want to rescue each exception error for each parameter from inside worker.

 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

Is there any way to do. Thanks u very much.

Upvotes: 0

Views: 150

Answers (1)

Masa Sakano
Masa Sakano

Reputation: 2267

I assume self.parameters are in your Model class instance. In that case, do as follows and you can reference them.

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

Note:

As a rule of thumb, it is recommended to limit the scope of rescue as narrow as possible. Do not include statements which should not raise Exceptions in your main clause (such as, @txt.save and FileUtils.rm_rf in your case). Also, it is far better to limit the class of an exception; for example, rescue Encoding::CompatibilityError instead of EncodingError, or EncodingError instaed of StandardError, and so on. Or, an even better way is to define your own Exception class and raise it deliberately.

Upvotes: 1

Related Questions