Created
August 26, 2010 09:31
-
-
Save ctrochalakis/551136 to your computer and use it in GitHub Desktop.
Using exception_notifier for rake tasks or scripts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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 |
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
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.