1

Started learning Ruby a week ago. The most frustrating part so far has been exception handling. Been looking for an example for what I want to do for hours.

I am looping through an array of API codes, grabbing text via Net::Http. Sometimes the grab returns nil or empty, and I'm trying to test for it in a way that will let me retry the grab on that exception until it works.

I am fairly certain I need to do something like

array.each do |api_key|
  begin
   result = # the code to grab the page via the API key

   if result.empty or result.nil
     raise SomeKindOfExceptionThing
   end

  rescue SomeKindOfExceptionThing
    puts "some error message"
    retry

  else
    # Act on the valid return for result
  end
end

I have no idea how to properly form this so it does what I want. Most of the documentation I've found on exceptions is for handling predefined types of errors or just a generic rescue.

1
  • 3
    Please, read the documentation carefully. The methods are named nil? and empty? not nil and empty. Commented Feb 3, 2016 at 22:16

2 Answers 2

4

As @eugen says your code will work. Not sure I see much benefit in raising the exception, though, in that particular example.

array.each do |api_key|
  result = # the code to grab the page via the API key 
  if result.empty || result.nil
    puts "some error message"
    redo
  end
  # Act on the valid return for result
end
Sign up to request clarification or add additional context in comments.

5 Comments

I think you confuse retry and redo.
Indeed; retry will go through all api keys again in case of an error, redo will only repeat the failed ones. +1 for doubting exceptions: they are the mechanism for non-local error handling. Instead of raising an exception and immediately rescuing it, if is much easier, shorter, and more performant.
@Stefan absolutely. I copied OP's code and didn't spot the mistake. Answer edited.
@Amadan absolutely. I copied OP's code and didn't spot the mistake. Answer edited.
I didn't know you could repeat a loop iteration without an exception. This is great, thanks.
0

Your code looks fine, you just need to define your exception class. Something like

class SomeKindOfExceptionThing < StandardError
end

should be enough (you might need a better name, though).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.