3

I have a rake task that loops through rows in CSV file, and inside that loop, there's a begin/rescue block to catch any possible raised exception. But when I run it, it keeps on saying 'rake aborted!' and it is not entering the rescue block

CSV.foreach(path, :headers => true) do |row|
  id = row.to_hash['id'].to_i
  if id.present?
    begin
      # call to mymethod
    rescue => ex
      puts "#{ex} error executing task"
    end
  end
end
...
def mymethod(...)
  ...
  begin
    response = RestClient.post(...)
  rescue => ex
    raise Exception.new('...')
  end
end

Expected: It should finish looping all the rows of the CSV

Actual result: It stops after reaching the 'raise' exception saying that:

rake aborted!

Exception: error message here

...

Caused by:

RestClient::InternalServerError: 500 Internal Server Error

Kok A.
  • 167
  • 1
  • 15
  • This looks like it could be a different issue - perhaps it's worth including your actual code @OdethA.? Is there a call to RestClient elsewhere in the task that could be throwing this? – SRack Jan 23 '19 at 15:30
  • @SRack, I edited the sample code above including the structure of the method being called – Kok A. Jan 23 '19 at 17:52

2 Answers2

1

You can use next to skip the faulty step of loop:

CSV.foreach(path, :headers => true) do |row|
  id = row.to_hash['id'].to_i
  if id.present?
    begin
      method_which_doing_the_staff
    rescue SomethingException
      next
    end
  end
end

And raise the exception inside your method:

def method_which_doing_the_staff
  stuff
  ...
  raise SomethingException.new('hasd')
end
barmic
  • 1,042
  • 7
  • 15
  • Hi Barmic, thanks for the suggestion. Unfortunately, I also did try that before. But it still got stopped by the exception. I updated the question to show the similar error I received when I run the task. – Kok A. Jan 23 '19 at 14:37
  • I don't think this would make any difference @barmic? `next` would be useful if used based on a condition, though switching out `puts` for this wouldn't change anything. – SRack Jan 23 '19 at 15:29
0

I solved this issue by just commenting out the line that is raising an exception because it seems like it the quickest fix for now.

# raise Exception.new('...')

I'm still open to other suggestions if there are any better ways to do it.

Kok A.
  • 167
  • 1
  • 15