Your browser (Internet Explorer 6) is out of date. It has known security flaws and may not display all features of this and other websites. Learn how to update your browser.
X

Posts tagged ‘exception-handling’

Post

Exception Notification in Rails

I bet you love getting e-mail. It makes you feel all warm and fuzzy inside to see that ‘new message’ indicator on your favorite mail app. I bet you love it even more when it’s from Rails – letting you know about an exception in your application. What? You don’t get any e-mail when that happens? Let’s remedy that.

There’s this guy…

Just add the following to your gemfile:

gem 'exception_notification'

Bundle it on up…

Configure any options in your ‘config.ru’ file (gem README). To make it run in production, add the following in your config/application.rb file:

MyApp::Application.config.middleware.use ExceptionNotifier,
  :email_prefix => "[MyApp] ",
  :sender_address => %{"Notifier" },
  :exception_recipients => %w{exceptions@somedomain.com}

And boom, now you’re getting all kinds of e-mails generated by your shoddy code! (Provided you have setup mail delivery in your Rails application.) Enjoy!

On a side note… I decided to add this in after the original posting. If you require a custom exception in your code (so what you are being notified of is clear to you), there is an easy way to do it. Just create a custom class that inherits from Exception like so:

class MyCustomException < Exception
end
 
raise MyCustomException, "I am a custom exception"

That will work – but let’s take it a step further. Instead of inheriting directly from Exception, it might be best to inherit from StandardError. The reason behind this is that StandardError deals with exceptions at the application level, whereas Exception itself may also catch exceptions at the environment level. So, for example:

class MyCustomError < StandardError
end

When inheriting from StandardError – the convention is to use the term ‘error’ rather than ‘exception’. Now you can throw all kinds of crazy custom exceptions (errors) ’til your heart’s content!