January 31, 2011

Rails exception_notification Setup

With any launched web app, it's a very good idea to set up some kind of exception notification - in fact, it's on my top 3 "Launch Checklist".

Exception Notification is a handy service that plugs into your existing app and sends you an email if (when) any exceptions are thrown in the course of people using your application. With Rails 3 and the exception_notification gem, it's almost laughably easy to set up.

First, add the following to your Gemfile:

gem "exception_notification",
    :git => "git://github.com/rails/exception_notification.git",
    :require => "exception_notifier"

Then, insert this little snippet in config/application.rb, in the config block:

# Exception Notification
config.middleware.use ExceptionNotifier, {
 :email_prefix => "[Website Error] ",
 :sender_address => '"Notifier" ',
 :exception_recipients => ['you@yourdomain.com']

That's it! Wasn't that easy?


If you're clicking through your application trying to get an exception thrown (but of course your application is written so well you frustratingly can't fire off an error), it might also be a good idea to create a method that tests your exception notification.

Just add a method that raises an exception in your app/controllers/application_controller.rb:

def test_exception
    raise 'Testing, 1 2 3.'

(Don't forget to add a route to config/routes.rb if you need it):

match "test_exception" => "application#test_exception_notification"

Now, you can visit http://yourwebapp.com/test_exception_notification to trigger the exception notification manually and test if the emailing works.

What if something goes wrong? All of the exception notification mailer's activity is logged, so go check out the relevant (development or production) log in log/

tail -f log/production.log

You also might want to turn off ActionMailer from sending email notifications when you're testing things out (application-wise, not exception notification-wise) on your development server. Just stick this code in config/environments/development.rb:

config.action_mailer.perform_deliveries = false

Cool, now you've got your very own exception notification set up! Happy debugging! (: