The Exception Notification Ruby gem is a great addition to any existing Rack or Rails application 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
  • Datadog
  • HipChat
  • IRC
  • Slack
  • Mattermost
  • Microsoft Teams
  • Amazon SNS
  • Google Chat
  • WebHook

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

This guide will cover the installation and setting-up on the gem in a Rails application.

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!

Include Custom Data in Notifications

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 Notifications

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!


One thought on “Setting Up and Testing Rails Exception Notification

Leave a Reply

Your email address will not be published. Required fields are marked *