Simon Lehmann

Web/mobile app developer from Perth, Western Australia

Setting up and Testing Rails Exception Notification

20 Jan 2017

The Exception Notification gem is a great addition to any existing app for notifying you with an email for every error that occurs, which you would otherwise not know about.

The gem also has build-in notifiers to send its notifications to other services like:

  • Campfire
  • HipChat
  • IRC
  • Slack
  • Mattermost
  • WebHook

Only the email notifier will be covered in this post. Check out the gem’s notifier documentation for additional implementation instructions.

Requirements

  • Ruby 2.0 or greater
  • Rails 4.0 or greater, Sinatra or another Rack-based application.

Getting Set Up

Add the following to your application’s Gemfile:

gem 'exception_notification'

Exception Notification can run in any environment you like, but usually you would only want it running in production. Add the following in your config/environments/production.rb:

Rails.application.config.middleware.use ExceptionNotification::Rack,
  email: {
    email_prefix: "[PREFIX] ", # Default: [ERROR]
    sender_address: %{"notifier" <[email protected]>},
    exception_recipients: %w{[email protected]}
  }

The email_prefix: option above is for prefixing the email subject lines. This option is optional and if not defined, will default to [ERROR].

Done!

Custom Data

For convenience, you can configure Exception Notification to include some extra values in its notifications, e.g: current_user. This can be achieved by adding the following to app/controllers/application_controller.rb:

class ApplicationController < ActionController::Base
  before_filter :prepare_exception_notifier

  private

  def prepare_exception_notifier
    request.env["exception_notifier.exception_data"] = {
      current_user: current_user
    }
  end
end

Testing

Checking to make sure everything is working is easy.

Add the following to config/routes.rb:

# Route for testing Exception Notification configuration
get "test_exception_notifier" => "application#test_exception_notifier"

Add the following to app/controllers/application_controller.rb:

def test_exception_notifier
  raise "Test Exception. This is a test exception to make sure the exception notifier is working."
end

Now you can navigate to http://domain.com/test_exception_notifier to trigger your test exception.

Happy debugging!