views:

78

answers:

3

I'm using some ruby code wrapped in a begin - rescue block but somehow it manages to still crash.

the block of code looks like this:

# Retrieve messages from server
def get_messages
  @connection.select('INBOX')
  @connection.uid_search(['ALL']).each do |uid|
    msg = @connection.uid_fetch(uid,'RFC822').first.attr['RFC822']
    begin
      process_message(msg)
      add_to_processed_folder(uid) if @processed_folder
    rescue
       handle_bogus_message(msg)
    end
    # Mark message as deleted 
    @connection.uid_store(uid, "+FLAGS", [:Seen, :Deleted])
  end
end

Given this code i would assume that if process_message or add_to_processed_folder could not execute then rescue would kick in and call handle_bogus_message. That being said I'm running this code in a production environment and sometimes when i "get" an email message (this is run from a rake task) it dies with a SyntaxError.

For a look at the error message check out http://pastie.org/1028479 and not that process_message that it is referring to is the same process_message above. Is there any reason why begin - rescue won't catch this exception?

+11  A: 

rescue without a parameter just rescues exceptions that inherit from StandardError. To rescue a SyntaxError use rescue SyntaxError or to rescue all exceptions use rescue Exception

sepp2k
The reason `rescue` doesn't rescue `Exception`s by default is that they're usually regarded as too severe to rescue.
Andrew Grimm
+2  A: 

rescue without any parameter accepts exceptions raised by StandardError class. Your error type is SyntaxError which is inherited from a different class called ScriptError. All these error classes are subclasses of Exception class. So as sepp2k suggested use rescue Exception to catch all kinds of exceptions.

Suman Mukherjee
A: 

You haven't mention which type of exception do you want to catch.

Just do on change in your code

rescue Exception => e
Dinesh Atoliya