public
Last active

Using exception_notifier for rake tasks or scripts

  • Download Gist
exception_notify_helper.rb
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
# 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" <noreply@skroutz.gr>',
:exception_recipients => 'dev@skroutz.gr',
:sections => [ 'backtrace']
}
ExceptionNotifier::Notifier.exception_notification(env, exception).deliver
raise exception
end

Does this works with this version? Where to put this code?

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.

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" <notifier@example.com>',
        :exception_recipients => 'notify@example.com',
        :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.

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.