3

I have the following line of code that is giving me an error:

rescue Timeout::Error => e
    logs.puts("Rescued a timeout error...#{e}")
    email_ids_all.each do |email_delete|

      call= "/api/v2/emails/#{email_delete}/"
      uri= HTTParty.delete("https://www.surveys.com#{call}",
          :basic_auth => auth,
          :headers => { 'ContentType' => 'application/x-www-form-urlencoded', 'Content-Length' => "0" }
      )
      puts "Deleted email #{email_delete}".green
      log.puts("Deleted email #{email_delete}")
    end
    abort #abort entire script after deleting emails
  end

The error I am receiving is this:

syntax error, unexpected keyword_rescue, expecting $end
  rescue Timeout::Error => e
        ^

Essentially I am just trying to run an API delete call if the script times out. It doesn't seem to matter what I put in the block for rescue though, I receive the same error. What's wrong with my syntax on the rescue method?

Luigi
  • 5,443
  • 15
  • 54
  • 108
  • 2
    Apparently you don't have `begin` in proper place. I can't say exactly unless you paste all your code. – Marek Lipka Aug 28 '13 at 14:36
  • Perhaps the answer is that I don't have `begin` at all. This is the entire code... – Luigi Aug 28 '13 at 14:39
  • I added begin and the script works fine- Not sure why the downvotes, but thanks for the help. Feel free to post your comment as an answer and I'll give you credit. – Luigi Aug 28 '13 at 14:41

1 Answers1

20

The format for using rescue is as follows:

begin
  # Code you want to run that might raise exceptions
rescue YourExceptionClass => e
  # Code that runs in the case of YourExceptionClass
rescue ADifferentError => e
  # Code that runs in the case of ADifferentError
else
  # Code that runs if there was no error
ensure
  # Code that always runs at the end regardless of whether or not there was an error
end

Here is a question with lots more information: Begin, Rescue and Ensure in Ruby?.

Community
  • 1
  • 1
  • 1
    Makes perfect sense- Thanks for the explanation, I was simply missing the `begin` piece. – Luigi Aug 28 '13 at 14:42
  • 1
    @LeviStanley it's worth noting that you don't need `begin` keyword if you want to rescue all code of method. – Marek Lipka Aug 28 '13 at 14:43
  • You mean implicit exception blocks (like when defining a method) or something else? –  Aug 28 '13 at 14:46
  • @LeviStanley yes, I mean implicit exception blocks. – Marek Lipka Aug 28 '13 at 14:47
  • 1
    @MarekLipka I added a link to another question; it includes a lot more information including mention of implicit exception blocks. –  Aug 28 '13 at 14:50