0

I'm trying to run a command that might fail sometimes. When it fails, it throws an exception.

What I'd like it to do is just log the error quietly and continue executing the next line below it, rather than aborting and going into the 'rescue' block. How should I approach this?

My current code is as follows:

  rescue_from 'Gibbon::MailChimpError' do |exception|
    logger.error("MAILCHIMP: #{exception}")
  end

When I call the Mailchimp API, sometimes there is an error, and this disrupts the flow of my application. I just want it to carry on executing as if nothing has happened, and just note there was an error in the log.

cjm2671
  • 18,348
  • 31
  • 102
  • 161
  • What `rescue` block? Where is your code? – Andrew Marshall Mar 12 '14 at 23:49
  • Updated with code as above. – cjm2671 Mar 13 '14 at 00:01
  • @cjm2671: Please update your question with the actual code. You have only shown us the rescue block. Not the actual call that results in exception – usha Mar 13 '14 at 00:21
  • I'm not sure that's relevant (it's a lot to paste, hence missing it out); what I want is whenever a line of code throws this exception, I just want it to carry on executing as normal ('skip over' in debug speak) – cjm2671 Mar 13 '14 at 01:41

1 Answers1

0

How about something like this:

def rescuing(&block)
  begin
    yield
  rescue NameError => e
    puts "(Just rescued: #{e.inspect})"
  end
end

rescuing do
  puts "This is dangerous"
  raise NameError
end

puts "... but I'm still alive"

Obviously, you'd have to replace NameError with the exception you want to be protected against.

agregoire
  • 2,022
  • 1
  • 16
  • 15
  • Oh that's very clever. I just tested it and it worked perfectly! Thank-you! I don't suppose there's a sexy way of packaging it up, such that you can do something like this_is_dangerous.try (just to make the code cleaner) – cjm2671 Mar 13 '14 at 12:17
  • You could always use the other block notation: `rescuing { puts "This is dangerous" }`. – agregoire Mar 13 '14 at 14:20