Skip to content

Instantly share code, notes, and snippets.

@ctrochalakis
Created August 26, 2010 09:31
Show Gist options
  • Save ctrochalakis/551136 to your computer and use it in GitHub Desktop.
Save ctrochalakis/551136 to your computer and use it in GitHub Desktop.
Using exception_notifier for rake tasks or scripts
# Exception notifier (rails3) only works as a rack middleware,
# but what if you need notifications inside a rake task or a script?
# This is a quick hack around that.
#
# Wrap your code inside an exception_notify block and you will be notified of exceptions
#
# exception_notify { clear_payments }
def exception_notify
yield
rescue Exception => exception
env = {}
env['exception_notifier.options'] = {
:email_prefix => '[Exception] ',
:sender_address => '"R2D2" <[email protected]>',
:exception_recipients => '[email protected]',
:sections => [ 'backtrace']
}
ExceptionNotifier::Notifier.exception_notification(env, exception).deliver
raise exception
end
@gregoryp
Copy link

It seems to me that you found where to put the code by the exceptions we received. :)
You should change exception_recipients to your e-mail if you like to receive the exceptions yourself.
Cheers.

@fabn
Copy link

fabn commented Aug 23, 2011

Yes, excuse me for the exception message ;-)

For the answer, I put the code inside my task namespace as in:

namespace :your_namespace do
  def exception_notify
    yield
  rescue Exception => exception
    env = {}
    env['exception_notifier.options'] = {
        :email_prefix => '[Exception] ',
        :sender_address => '"Exception notifier" <[email protected]>',
        :exception_recipients => '[email protected]',
        :sections => ['backtrace']
    }
    ExceptionNotifier::Notifier.exception_notification(env, exception).deliver
    raise exception
  end

  desc "Your task description"
  task :your_task => :environment do
    exception_notify { task_actual_code }
  end
end

I posted a question on Stack Overflow about this, if you want to join the discussion you're welcome.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment