Honeybadger for Ruby

Source CodeRuby Gem

Getting Started

Honeybadger works out of the box with all popular Ruby frameworks. Installation is just a matter of including the gem and setting your API key. In this section, we'll cover the basics. More advanced installations are covered later.

1. Install the gem

The first step is to add the honeybadger gem to your Gemfile:

gem 'honeybadger'

Tell bundler to install:

$ bundle install

2. Set your API key

Next, you'll set the API key for this project.

$ bundle exec honeybadger install [YOUR API KEY HERE]

This will generate a config/honeybadger.yml file. If you don't like config files, you can place your API key in the $HONEYBADGER_API_KEY environment variable.

Heroku installation

If your app is deployed to heroku, you can configure Honeybadger on your dynos like so:

$ bundle exec honeybadger heroku install [YOUR API KEY HERE]

This will automatically add a HONEYBADGER_API_KEY environment variable to your remote Heroku config and configure deploy notifications.

This step isn't necessary if you're using our Heroku add-on.

3. Set up your code

Rails

You're done! Any rake tasks and job queues that load the Rails environment are also covered.

For more info, check out our screencast on getting up and running with Honeybadger and Rails:

Using the Honeybadger gem with Rails

Sinatra

All you need to do is to include the honeybadger gem:

# Always require Sinatra first.
require 'sinatra'
# Then require honeybadger.
require 'honeybadger'
# Define your application code *after* Sinatra *and* honeybadger:
get '/' do
  raise "Sinatra has left the building"
end

To see an example of a sinatra implementation, check out this video:

Using the Honeybadger gem with Sinatra

Rack

With rack, you have to do things manually, but it's still just a few lines of code:

require 'rack'

# Load the gem
require 'honeybadger'

# Write your app
app = Rack::Builder.app do
  run lambda { |env| raise "Rack down" }
end

# Use Honeybadger's rack middleware
use Honeybadger::Rack::ErrorNotifier

run app

Plain Ruby

To use Honeybadger without any of the automatic integrations, require honeybadger/ruby instead of require 'honeybadger':

require 'honeybadger/ruby'

begin
  # Failing code
rescue => exception
  Honeybadger.notify(exception)
end

All of the public API methods are still available, but none of the plugins, framework integrations, or hooks are run. You will need to manually set up your own middleware and hooks for error monitoring in whatever frameworks you use.

Configuration

There are a few ways to configure the Honeybadger gem. You can use a YAML config file. You can use environment variables. You can use Ruby. Or you can use a combination of the three.

We put together a short video highligting a few of the most common configuration options:

Advanced Honeybadger Gem Usage

YAML Configuration File

By default, Honeybadger looks for a honeybadger.yml configuration file in the root of your project, and then config/honeybadger.yml (in that order).

Here's what the simplest config file looks like:

---
api_key: "my_api_key"

Nested Options

Some configuration options are written in YAML as nested hashes. For example, here's what the logging.path and request.filter_keys options look like in YAML:

---
logging:
  path: "/path/to/honeybadger.log"
request:
  filter_keys:
    - "credit_card"

Environments

Environment-specific options can be set by name-spacing the options beneath the environment name. For example:

---
api_key: "my_api_key"
production:
  logging:
    path: "/path/to/honeybadger.log"
    level: "WARN"

ERB and Regex

The configuration file is rendered using ERB. That means you can set configuration options programmatically. You can also include regular expressions. Here's what that looks like:

---
api_key: "<%= MyApplication.config.api_key %>"
request:
  filter_keys:
    - !ruby/regexp '/credit_card/i'

Configuring with Environment Variables (12-factor style)

All configuration options can also be read from environment variables (ENV). To do this, uppercase the option name, replace all non-alphanumeric characters with underscores, and prefix with HONEYBADGER_. For example, logging.path becomes HONEYBADGER_LOGGING_PATH:

export HONEYBADGER_LOGGING_PATH=/path/to/honeybadger.log

ENV options override other options read from framework or honeybadger.yml sources, so both can be used together.

Configuration via Ruby (programmatic)

To configure Honeybadger from Ruby, use Honeybadger.configure:

Honeybadger.configure do |config|
  config.api_key = 'project api key'
  config.exceptions.ignore += [CustomError]
end

Configuration Options

You can use any of the options below in your config file, or in the environment.

Option Type Description
api_key String The API key for your Honeybadger project.
Default: nil
env String The environment the app is running in. In Rails this defaults to Rails.env.
Default: nil
report_data Boolean Enable/disable reporting of data. Defaults to false for "test", "development", and "cucumber" environments.
Default: true
root String The project's absolute root path.
Default: Dir.pwd
revision String The project's git revision.
Default: revision detected from git
hostname String The hostname of the current box.
Default: Socket.gethostname
backend String An alternate backend to use for reporting data.
Default: nil
debug Boolean Enables verbose debug logging.
Default: false
send_data_at_exit Boolean Finish sending enqueued exceptions before allowing program to exit.
Default: true
disabled Boolean Prevents Honeybadger from starting entirely.
Default: false
config_path String The path of the honeybadger config file. Can only be set via the $HONEYBADGER_CONFIG_PATH environment variable
development_environments Array Environments which will not report data by default (use report_data to enable/disable explicitly).
Default: ["development", "test", "cucumber"]
plugins Array An optional list of plugins to load. Default is to load all plugins.
Default: []
skipped_plugins Array An optional list of plugins to skip.
Default: []
 
LOGGING
logging.path String The path (absolute, or relative from config.root) to the log file. Defaults to the rails logger or STDOUT. To log to standard out, use 'STDOUT'.
Default: nil
logging.level String The log level. Does nothing unless logging.path is also set.
Default: INFO
 
HTTP CONNECTION
connection.secure Boolean Use SSL when sending data.
Default: true
connection.host String The host to use when sending data.
Default: api.honeybadger.io
connection.port Integer The port to use when sending data.
Default: 443
connection.http_open_timeout Integer The HTTP open timeout when connecting to the server.
Default: 2
connection.http_read_timeout Integer The HTTP read timeout when connecting to the server.
Default: 5
connection.proxy_host String The proxy host to use when sending data.
Default: nil
connection.proxy_port Integer The proxy port to use when sending data.
Default: nil
connection.proxy_user String The proxy user to use when sending data.
Default: nil
connection.proxy_pass String The proxy password to use when sending data.
Default: nil
 
REQUEST DATA FILTERING
request.filter_keys Array  A list of keys to filter when sending request data. In Rails, this also includes existing params filters.
Default: ['password', 'password_confirmation']
request.disable_session Boolean Prevent session from being sent with request data.
Default: false
request.disable_params Boolean Prevent params from being sent with request data.
Default: false
request.disable_environment Boolean Prevent Rack environment from being sent with request data.
Default: false
request.disable_url Boolean Prevent url from being sent with request data (Rack environment may still contain it in some cases).
Default: false
 
USER INFORMER
user_informer.enabled Boolean Enable the UserInformer middleware. The user informer displays information about a Honeybadger error to your end-users when you display a 500 error page. This typically includes the error id which can be used to reference the error inside your Honeybadger account.  Learn More
Default: true
user_informer.info String Replacement string for HTML comment in templates.
Default: 'Honeybadger Error {{error_id}}'
 
USER FEEDBACK
feedback.enabled Boolean Enable the UserFeedback middleware. Feedback displays a comment form to your-end user when they encounter an error. When the user creates a comment, it is added to the error in Honeybadger, and a notification is sent.  Learn More
Default: true
 
EXCEPTION REPORTING
exceptions.ignore Array A list of exception class names to ignore (appends to defaults).
Default: ['ActionController::RoutingError', 'AbstractController::ActionNotFound', 'ActionController::MethodNotAllowed', 'ActionController::UnknownHttpMethod', 'ActionController::NotImplemented', 'ActionController::UnknownFormat', 'ActionController::InvalidAuthenticityToken', 'ActionController::InvalidCrossOriginRequest', 'ActionDispatch::ParamsParser::ParseError', 'ActionController::BadRequest', 'ActionController::ParameterMissing', 'ActiveRecord::RecordNotFound', 'ActionController::UnknownAction', 'CGI::Session::CookieStore::TamperedWithCookie', 'Mongoid::Errors::DocumentNotFound', 'Sinatra::NotFound']
exceptions.ignore_only Array A list of exception class names to ignore (overrides defaults).
Default: []
exceptions. ignored_user_agents Array A list of user agents to ignore.
Default: []
exceptions.rescue_rake Boolean Enable rescuing exceptions in rake tasks.
Default: true when run in background; false when run in terminal.
exceptions.notify_at_exit Boolean Report unhandled exception when Ruby crashes (at_exit).
Default: true.
exceptions.source_radius Integer The number of lines before and after the source when reporting snippets.
Default: 2
exceptions.local_variables Boolean Enable sending local variables. Requires the binding_of_caller gem.
Default: false
exceptions.unwrap Boolean Reports #original_exception or #cause one level up from rescued exception when available.
Default: false
 
SIDEKIQ
sidekiq.attempt_threshold Integer The number of attempts before notifications will be sent.
Default: 0
sidekiq.use_component Boolean Automatically set the component to the class of the job. Helps with grouping.
Default: true
DELAYED JOB
delayed_job.attempt_threshold Integer The number of attempts before notifications will be sent.
Default: 0
SHORYUKEN
shoryuken.attempt_threshold Integer The number of attempts before notifications will be sent.
Default: 0
SINATRA
sinatra.enabled Boolean Enable Sinatra auto-initialization.
Default: true

Public Methods

What follows is a summary of the gem's most commonly-used public methods. For a more authoritative list, read the full API documentation.

Honeybadger.context(): Set metadata to be sent if an exception occurs

Sometimes, default exception data just isn't enough. If you have extra data that will help you in debugging, send it as part of an error's context. View full method documentation

Global context is stored in a thread local variable and automatically reported with any exception which occurs within the current thread's execution.

Use this method if:

  • You want to record the current user's id at the time of an exception
  • You need to send raw POST data for use in debugging
  • You have any other metadata you'd like to send with an exception

Examples:

Honeybadger.context({my_data: 'my value'})

# Inside a Rails controller:
before_action do
  Honeybadger.context({user_id: current_user.id})
end

# Clearing global context:
Honeybadger.context.clear!

# Fetching current context
Honeybadger.get_context


Honeybadger.notify(): Send an exception to Honeybadger.

You normally won't have to use this method. Honeybadger detects and reports errors automatically in Rails and other popular frameworks. But there may be times when you need to manually control exception reporting. View full method documentation

Use this method if:

  • You've rescued an exception, but still want to report it
  • You need to report an exception outside of a supported framework.
  • You want complete control over what exception data is sent to us.

Examples:

# Sending an exception that you've already rescued
begin
  fail 'oops'
rescue => exception
  Honeybadger.notify(exception)
end


Honeybadger.configure(): Configure Honeybadger from Ruby

This method allows you to configure Honeybadger at runtime.

Use this method if:

  • You want to change Honeybadger's configuration from inside Ruby rather than (or in addition to) using the honeybadger.yml file or environment variables.

Examples:

Honeybadger.configure do |config|
  config.api_key = 'project api key'
  config.exceptions.ignore += [CustomError]
end


Honeybadger.exception_filter(): Programmatically ignore exceptions

This method lets you add a callback that will be run every time an exception is about to be reported to Honeybadger. If your callback returns a truthy value, the exception won't be reported. View full method documentation

Use this method if:

  • You need to ignore exceptions that meet complex criteria
  • The built-in configuration options for filtering based on exception class and user agent aren't enough

Examples:

# Here's how you might ignore exceptions based on their error message:
Honeybadger.exception_filter do |notice|
  notice[:error_message] =~ /sensitive data/
end

You can access any attribute on the notice argument by using the [] syntax. For a full list of attributes, see the documentation for Notice Here are a few examples to get you started:

Honeybadger.exception_filter do |notice|
  notice[:exception].class < MyError &&
  notice[:params][:name] =~ "bob" &&
  notice[:context][:current_user_id] != 1
end

WARNING: While it is possible to use this callback to modify the data that is reported to Honeybadger, this is not officially supported and may not be allowed in future versions of the gem.


Honeybadger.exception_fingerprint(): Customize your error grouping.

This method lets you add a callback that should return a unique string given a Honeybadger::Notice instance. All notices which match the same string will be grouped together in Honeybadger.

Use this method if:

  • You currently receive too many error notifications
  • You want to group some errors together which are currently unique
  • You don't want to group some errors which are currently grouped

Examples:

Honeybadger.exception_fingerprint do |notice|
  [notice[:error_class], notice[:component], notice[:backtrace].to_s].join(':')
end


Honeybadger.backtrace_filter(): Filter your backtrace.

This method allows you to add a callback which modifies each line of the backtrace before a notification happens.

Use this method if:

  • You want to change or sanitize common data in your exception backtraces

Examples:

Honeybadger.backtrace_filter do |line|
  line.gsub(/^\/my\/unknown\/bundle\/path/, "[GEM_ROOT]")
end

Deployment tracking

Honeybadger has an API to keep track of project deployments. Whenever you deploy, all errors for that environment will be resolved automatically. You can choose to enable or disable the auto-resolve feature from your Honeybadger project settings page.

Capistrano Deployment Tracking

In order to track deployments using Capistrano, simply require Honeybadger's Capistrano task in your Capfile file:

require "capistrano/honeybadger"

If you ran the honeybadger install command in a project that was previously configured with Capistrano, we already added this for you.

Adding options to your  config/deploy.rb file allows you to customize how the deploy task is executed. The syntax for setting them looks like this:

set :honeybadger_env, "preprod"

You can use any of the following options when configuring capistrano.

Option
honeybadger_user Honeybadger will report the name of the local user who is deploying (using whoami or equivalent). Use this option to to report a different user.
honeybadger_env Honeybadger reports the environment supplied by capistrano by default. Use this option to change the reported environment.
honeybadger_api_key Honeybadger uses your configured API key by default. Use this option to override.
honeybadger_async_notify Run deploy notification task asynchronously using nohup. True or False. Defaults to false.
honeybadger_server The api endpoint that receives the deployment notification.
honeybadger The name of the honeybadger executable. Default: "honeybadger"

Heroku Deployment Tracking

Deploy tracking via Heroku is implemented using Heroku's free deploy hooks addon. To install the addon and configure it for Honeybadger, run the following CLI command from your project root:

$ bundle exec honeybadger heroku install_deploy_notification

If the honeybadger CLI command fails for whatever reason, you can add the deploy hook manually by running:

$ heroku addons:add deployhooks:http --url="https://api.honeybadger.io/v1/deploys?deploy[environment]=production&deploy[local_username]={{user}}&deploy[revision]={{head}}&api_key=asdf" --app app-name

You should replace the api key and app-name with your own values. You may also want to change the environment (set to production by default).

Deployment Tracking Via command line

We provide a CLI command to send deployment notifications manually:

bundle exec honeybadger deploy --environment=production

Run  bundle exec honeybadger help deploy for all available options.

Custom Error Pages

The Honeybadger gem has a few special tags that it looks for whenever you render an error page. These can be used to display extra information about the error, or to ask the user for information about how they triggered the error.

Displaying Error ID

When an error is sent to Honeybadger, our API returns a unique UUID for the occurrence within your project. This UUID can be automatically displayed for reference on Rails error pages (e.g. public/500.html) or any rack output by including the Honeybadger::UserInformer middleware.

To include the error id, simply place this magic HTML comment on your error page:

<!-- HONEYBADGER ERROR -->

By default, we will replace this tag with:

Honeybadger Error {{error_id}}

Where {{error_id}} is the UUID. You can customize this output by overriding the user_informer.info option in your honeybadger.yml file (you can also enabled/disable the middleware):

user_informer:
  enabled: true
  info: "Error ID: {{error_id}}"

You can use that UUID to load the error at the site by going to  https://www.honeybadger.io/notice/UUID.

Collecting User Feedback

When an error is sent to Honeybadger, an HTML form can be generated so users can fill out relevant information that led up to that error. Feedback responses are displayed inline in the comments section on the fault detail page.

To include a user feedback form on your error page, simply add this magic HTML comment:

<!-- HONEYBADGER FEEDBACK -->

You can change the text displayed in the form via the Rails internationalization system. Here's an example:

# config/locales/en.yml
en:
  honeybadger:
    feedback:
      heading: "Care to help us fix this?"
      explanation: "Any information you can provide will help us fix the problem."
      submit: "Send"
      thanks: "Thanks for the feedback!"
      labels:
        name: "Your name"
        email: "Your email address"
        comment: "Comment (required)"

Honeybadger CLI

The Honeybadger CLI provides a Command Line Interface for various Honeybadger-related programs and utilities. All features are available through the honeybadger command and can be used independently of Bundler/Rails.

When using the honeybadger gem with Bundler, run bundle exec honeybadger.

To use outside of bundler, install the Honeybadger gem with gem install honeybadger and then run honeybadger.

CLI Configuration

The honeybadger command optionally reads configuration from the following locations. Each location in the list takes precedence over the previous location:

  1. ~/honeybadger.yml
  2. ./config/honeybadger.yml
  3. ./honeybadger.yml
  4. Rails/Ruby configuration (only when called from a Rails app root)
  5. Environment variables
  6. Command-line flags (i.e. --api-key)

The following configuration options are used by the CLI when applicable: api_key, env. See Configuration Options

All other options must be passed as command-line flags.

CLI Commands

The following commands are available through the honeybadger CLI:

Command Description
honeybadger deploy Notify Honeybadger of deployment
honeybadger exec Execute a command. If the exit status is not 0, report the result to Honeybadger
honeybadger help Describe available commands or one specific command
honeybadger heroku Manage Honeybadger on Heroku
honeybadger install Install Honeybadger into a new project
honeybadger notify Notify Honeybadger of an error
honeybadger test Send a test notification from Honeybadger

For additional info about each command, run honeybadger help.

Rails initialization

When run from the root of a Rails project, the honeybadger command will load the Rails environment so that any framework/programmatic configuration is picked up.

Cron/command line monitoring

honeybadger exec can be used from the command line/terminal to monitor failed commands. To use it, prefix any normal command with honeybadger exec (much like bundle exec):

$ honeybadger exec my-command --my-flag

If the command executes successfully, honeybadger exits with code 0. It prints any output from the command by default. To use with cron's automatic email feature, use the --quiet flag, which will suppress all standard output from the origin command unless the command fails and the Honeybadger notification fails, in which case it will dump the output so that cron can send a backup email notification.

For full usage run honeybadger help exec.

Notify from the command line

To send a Honeybadger notification from the command line/terminal, use honeybadger notify:

$ honeybadger notify --message "This is an error from the command line"

For full usage run honeybadger help notify.

Integration Testing

It is possible to test Honeybadger's integration with your application using the included test backend.

The test backend replaces the default server backend with a stub that records error notices rather than sending them, allowing all but the HTTP notification itself to be verified. Alternatively, you could use something like WebMock to perform a similar test using the "server" backend.

Configuring the test backend

To use the test backend, set the backend configuration option to "test" in honeybadger.yml for your test environment only:

api_key: 'project api key'
test:
  backend: test

You can also use the HONEYBADGER_BACKEND environment variable to configure the test backend. Note that you must also configure your API key for the test to succeed.

Writing the integration test

The test backend can be used in any testing framework to test any code which reports an error with Honeybadger.notify. A common scenario is to test the Rails-integration which reports exceptions in a Rails controller automatically.

The following example uses RSpec to test error notification in a Rails controller.

First, create the controller:

# app/controllers/honeybadger_test_controller.rb
class HoneybadgerTestController < ApplicationController
  ERROR = RuntimeError.new("testing reporting an error to Honeybadger")

  def index
    raise ERROR
  end
end

Next, create a route. For security, it's a good idea to enable the route only in the test environment:

  # config/routes.rb

  # ...
  get '/test/honeybadger' => 'honeybadger_test#index' if Rails.env.test?

Finally, create the integration test:

# spec/features/honeybadger_spec.rb
require 'rails_helper'

describe "error notification" do
  it "notifies Honeybadger" do
    expect {
      # Code to test goes here:
      expect { visit '/test/honeybadger' }.to raise_error(HoneybadgerTestController::ERROR)

      # Important: `Honeybadger.flush` ensures that asynchronous notifications
      # are delivered before the test's remaining expectations are verified.
      Honeybadger.flush
    }.to change(Honeybadger::Backend::Test.notifications[:notices], :size).by(1)
    expect(Honeybadger::Backend::Test.notifications[:notices].first.error_message).to eq('testing reporting an error to Honeybadger')
  end
end

Security

Proxies

If your application requires a proxy to communicate with the outside world, you can still use Honeybadger to report errors. Here's an example proxy configuration:

connection:
  proxy_host: 'proxy.host.com'
  proxy_port: 4038
  proxy_user: 'foo' # optional
  proxy_pass: 'bar' # optional

Sensitive data

You have complete control over the data that honeybadger reports when an error occurs. You can remove individual attributes, or disable the reporting of entire sections of data.

Filtering Specific Attributes

By default, we filter the password and password_confirmation, as well as any params specified in Rails' params_filters.

You can configure the gem to filter additional data from the params, session, environment and cookies hashes. To do so, use the request.filter_keys setting.

When you add an attribute name to request.filter_keys, that attribute will be removed from any exceptions before they are reported to us.

Here's an example honeybadger.yml:

request:
  filter_keys:
    - password
    - password_confirmation
    - credit_card_number

The configuration above will filter out params[:credit_card_number], session[:credit_card_number], cookies[:credit_card_number], and Rails.env["credit_card_number"], as well as the password and password_confirmation attributes.

Regular expressions (regex) are also allowed. The configuration below will filter out any keys that are named anything matching /credit_card/i.

request:
  filter_keys:
    - !ruby/regexp '/credit_card/i'

Disable data completely

You can turn off reporting of params, session and environment data entirely. Here are the configuration options to do it:

request:
  disable_session: true # Don't report session data
  disable_params: true # Don't report request params
  disable_environment: true # Don't report anything from Rack ENV
  disable_url: true # Don't report the request URL

Testing

Disable Honeybadger in Tests

If you're using Rails, Honeybadger will automatically disable error notifications during testing.

For other frameworks, you can disable the gem during testing by setting the HONEYBADGER_ENV environment variable. One easy way to do this is to add the following line to your test or spec helper:

ENV['HONEYBADGER_ENV'] = 'test'

Write tests using Honeybadger

It is possible to test the error notification process. Honeybadger will do everything short of actually send the exception to our servers. One issue that can complicate things is that our error notification code is asynchronous. However you can use the Honeybadger.flush method to force all exceptions to be reported in a synchronous (blocking) fashion. Here's how you'd do that:

# Without a block:
it "sends a notification to Honeybadger" do
  expect {
    Honeybadger.notify(StandardError.new('test backend'))
    Honeybadger.flush
  }.to change(Honeybadger::Backend::Test.notifications[:notices], :size).by(1)
end

# With a block:
it "sends a notification to Honeybadger" do
  expect {
    Honeybadger.flush do
      50.times do
        Honeybadger.notify(StandardError.new('test backend'))
      end
    end
  }.to change(Honeybadger::Backend::Test.notifications[:notices], :size).by(50)
end

To have these tests run successfully, you must have the HONEYBADGER_BACKEND option set to "test". One way to do that is just to put ENV['HONEYBADGER_BACKEND'] = "test" in your test or spec helper file. The value can be set like your other configuration options as well.

Working With Exceptions

Add Context Data

You can attach custom metadata to the exception reports sent to Honeybadger. This is simple but very powerful capability. For example, you could:

  • Record the current user's email or id when they come across an error.
  • Give yourself hits about exactly what was happening when an error occurred. i.e. If the error happened when you were batch-processing a bunch of files, which file were you processing?
  • Give yourself information about the context in which the error occurred.

You add context information to an error using the Honeybadger.context method. You can call it from anywhere in your application. Then if an exception occurs, it will pull the context that you saved and send it along with the exception.

In the example below, we're setting the current user's email and id, using a Rails before_action callback:

class ApplicationController < ActionController::Base
  before_action do
    Honeybadger.context({
      :user_id => current_user.id,
      :user_email => current_user.email
    }) if current_user
  end
end

Now, whenever an error occurs, Honeybadger will display the affected user's id and email address, if available.

You can call context as many times as you like. Subsequent calls will merge the existing hash with any new data.

Honeybadger discards he context when each web request is complete. So you'll always start each new request with a blank slate.

Report a rescued exception

To manually send exceptions to Honeybadger, use the Honeybadger.notify method.

# ...
rescue => ex
  # Ignores "noisy" exceptions like ActiveRecord::RecordNotFound
  Honeybadger.notify(ex)
  flash[:failure] = 'Encryptions could not be rerouted, try again.'
end
# ...

Errors which have been ignored via configuration or callbacks will not be reported. To skip all ignore logic, use the :force option.

# ...
rescue => ex
  # Always sends the exception
  Honeybadger.notify(ex, force: true)
  flash[:failure] = 'Encryptions could not be rerouted, try again.'
end
# ...

Report a custom exception

The Honeybadger.notify can accept a hash, allowing you to pass in whatever data you like. This means that you can report "exceptions" that aren't technically exceptions, but which may still be useful.

begin
  params = {
    :id => 1,
    :class => MyClass,
    :foo => "bar"
  }
  my_unpredictable_method(*params)
rescue => e
  Honeybadger.notify(
    :error_class => "Special Error",
    :error_message => "Special Error: #{e.message}",
    :parameters => params
  )
end

Valid keyword arguments:

  • :error_class - Use this to group similar errors together. When Honeybadger catches an exception it sends the class name of that exception object.
  • :error_message - This is the title of the error you see in the errors list. For exceptions it is "#{exception.class.name}: #{exception.message}"
  • :parameters - While there are several ways to send additional data to Honeybadger, passing a Hash as :parameters as in the example above is the most common use case. When Honeybadger catches an exception in a controller, the actual HTTP client request parameters are sent using this key.

Honeybadger merges the hash you pass with these default options:

{
  :api_key => 'secret',
  :error_message => 'Notification',
  :backtrace => caller,
  :parameters => {},
  :session => {},
  :context => {}
}

You can override any of those parameters.

Honeybadger.notify will not report any "ignored" exceptions, unless you force it to by using the force argument.

Honeybadger.notify(error_class: 'MyError', message: 'Boom!', force: true)

Ignore by class

Some exceptions aren't very useful and are best ignored. By default, we ignore the following:

ActiveRecord::RecordNotFound
ActionController::RoutingError
ActionController::InvalidAuthenticityToken
ActionController::UnknownAction
ActionController::UnknownFormat
AbstractController::ActionNotFound
CGI::Session::CookieStore::TamperedWithCookie
Mongoid::Errors::DocumentNotFound
Sinatra::NotFound
ActionController::UnknownFormat

To ignore additional errors, use the exceptions.ignore configuration option. The gem will ignore any exceptions matching the string, regex or class that you add to exceptions.ignore.

exceptions:
  ignore:
    - 'MyError'
    - !ruby/regexp '/Ignored$/'
    - !ruby/class 'IgnoredError'

Subclasses of ignored classes will also be ignored, while strings and regexps are compared with the error class name only.

To override the default ignored exceptions, use the exceptions.ignore_only option instead:

exceptions:
  ignore_only:
    - 'MyError'

Ignore by browser

To ignore certain user agents, use the exceptions.ignored_user_agents config option. You can specify strings or regular expressions:

exceptions:
  ignored_user_agents:
    - 'Exact User Agent'
    - !ruby/regexp '/Bing/i'

Ignore by environment

Honeybadger ignores errors in development and test environments by default. You can enable or disable error reporting for a specific environment by using the [environment name].report_data configuration option:

staging:
  report_data: false

You may alternatively set HONEYBADGER_REPORT_DATA=false in your app's ENV.

We ask that you not enable error reporting for your test environment. It doesn't do anyone any good. :)

Dynamically ignore errors

To ignore errors with some custom logic, you can use callback code.

Local Variables

It's possible to capture the local variables that were in scope when an exception was raised. This can be really handy when debugging apps in staging. It's not recommended for production, as there is a significant performance hit.

To enable local variables, add the binding_of_caller gem to your app. Then enable local variables via the exceptions.local_variables configuration option.

exceptions:
  local_variables: true

Note that local variables are converted to string and truncated before being reported to Honeybadger.

Multiple Projects

To send errors to another Honeybadger project, configure an additional agent:

OtherBadger = Honeybadger::Agent.new

OtherBadger.configure do |config|
  config.api_key = 'project api key'
end

begin
  # Failing code
rescue => exception
  OtherBadger.notify(exception)
end

Agents do not use the global honeybadger.yml or environment variable configuration and must be configured manually after they are instantiated.

Troubleshooting

Command line utility

If you get an error while running the honeybadger command line utility:

  1. Try prefixing the command with bundle exec...even if you normally rely on bin-stubs to do this for you.
  2. Check honeybadger help if you're having trouble with the syntax for a specific command.
  3. Try enabling verbose logging to get more info.
  4. Ask Us! We're always here to help. Just copy the terminal output and email it to us at support@honeybadger.io .

Missing Exceptions

Have you triggered a exception, but it hasn't been reported? There are a few common reasons for this:

  1. The exception is being swallowed by your code and isn't being reported to us. This can happen when you have a rescue_from statement in your Rails controllers. The solution is to notify us manually of the rescued exception by using Honeybadger.notify(exception).
  2. The particular exception you're looking for is one which we ignore by default. This is controlled by the exceptions.ignore configuration value.
  3. You're trying to send an exception in Development mode. By default, exceptions in development aren't reported to us. You can override this with the report_data configuration option.
  4. You're trying to use IRB or the Rails console to send a test exception. The gem is designed to avoid sending errors from the console.
  5. By default we only send notifications the first time an exception happens, and when it re-occurs after being marked resolved. If an exception happens 100 times, but was never resolved you'll only get 1 email about it.

Send a Test Exception

You can send a test exception using the honeybadger command line utility:

$ honeybadger test

Verbose Logging

By default, Honeybadger is quiet when your log level is set to INFO (most production environments). If you would like to be notified via logs when Honeybadger completes a successful notification, set the logging.debug option to true in your honeybadger.yml config file:

logging:
  debug: true

You can also use the environment variables HONEYBADGER_LOGGING_DEBUG and HONEYBADGER_LOGGING_PATH to configure these options via the command line.

Supported Frameworks

Here at Honeybadger, we try to support every popular framework and tool that Ruby developers use. If we're missing your favorite tool in the lists below, let us know!

Ruby

Ruby Interpreter Supported Version
MRI >= 2.1.0
JRuby >= 9.1

Web Frameworks

Framework Version Native?
Rails >= 3.2 yes
Sinatra >= 1.2.1 yes
Rack >= 1.0 middleware

Rails and Sinatra are supported natively (install/configure the gem and you're done). For vanilla Rack apps, we provide a collection of middleware that must be installed manually.

To use Rails 2.x, you'll need to use an earlier version of the Honeybadger gem. Go to version 1.x of the gem docs.

Integrating with other libraries/frameworks is simple! See the documentation to learn about our public API, and see Contributing to suggest a patch.

Job Queues

Library Version Native?
Sidekiq any yes
Resque any yes
Delayed Job any yes
Sucker Punch any yes
Shoryuken any yes