Adding Context to Exception Classes

We recently shipped version 3.2 of the honeybadger Ruby Gem, which includes a new feature to make it easier to add context to your error reports.

We recently shipped version 3.2 of the honeybadger Ruby Gem, which includes a new feature to make it easier to add context to your error reports.

tl;dr

The honeybadger gem now supports defining the #to_honeybadger_context method on any exception class. When an instance of that exception is raised and reported to Honeybadger, its context will be automatically included in the error report:

class MyError < StandardError
  attr_reader :custom_attribute

  def initialize(err, custom_attribute)
    @custom_attribute = custom_attribute
    super(err)
  end

  def to_honeybadger_context
    {
      custom_attribute: custom_attribute
    }
  end
end

raise MyError.new("Something went wrong", { foo: 'bar' })
# Honeybadger context will include:
# {
#   custom_attribute: {
#     foo: 'bar'
#   }
# }

What is Context?

Context allows you to send additional data to Honeybadger when an error occurs in your application. In Rails, you can set context for the current request using the Honeybadger.context method, which is provided by our Ruby gem:

Honeybadger.context({
  user_email: 'user@example.com'
})

Every error which occurs in the current request (or job if you're running a background worker) will have its own unique context data.

Your context data can be anything, but often includes things likes the user id or email address of the currently logged in user, some raw POST data or other related payload to aid debugging, id of a background job, etc.

You can also add local context when reporting an error manually:

Honeybadger.notify(exception, context: {
  user_email: 'user@example.com'
})

Fun fact: while context can be anything, Honeybadger has a few "special" context keys. For instance, if you include the user_email key with your error reports, Honeybadger will create a report of affected users for each error.

Adding Context from Exceptions

Some context is specific to an exception itself, rather than a request. For instance, say we're making an HTTP request using the faraday gem:

require 'faraday'

conn = Faraday.new(:url => 'http://example.com') do |faraday|
  faraday.response :raise_error # Raises an error if the request isn't successful
  faraday.adapter  Faraday.default_adapter
end

response = conn.get('/does-not-exist') # => Faraday::ResourceNotFound

The above code raises the following exception:

Faraday::ResourceNotFound: the server responded with status 404

Honeybadger will automatically report this error (assuming it's configured to do so), but it won't have any information about the response object. This information would be nice to have, especially for less obvious server errors, such as a 500 response.

Looking at the definition of Faraday::ResourceNotFound on GitHub, we see that it's actually a type of ClientError, and ClientError defines an attribute that stores the response object on each instance.

Using this information, we can rescue all instances of Faraday::ClientError and use Honeybadger.notify to add some response data to the context:

begin
  response = conn.get('/does-not-exist')
rescue Faraday::ClientError => err
  Honeybadger.notify(err, context: {
    response_status:  err.response.status,
    response_headers: err.response.headers
  })
  # Additional error handling...
end

This allows us to report failed requests to Honeybadger along with some extra information about the response.

We use this pattern for adding exception-specific context when an error occurs, and while it works, it clutters our code with rescue statements and custom notification logic, which is messy and adds a lot of overhead to our code. The good news: there's a better way!

New Feature: Exception-level Context

Instead of reporting the error manually, the context can now be defined on the exception class itself, and Honeybadger will pick it up automatically, no matter where the error is ultimately reported.

Revisiting the previous example, rather than adding an ugly rescue statement, let's allow Honeybadger's built-in reporting to handle the exception:

response = conn.get('/does-not-exist') # => Faraday::ResourceNotFound

Instead, let's add the #to_honeybadger_context method to Faraday::ClientError, which is a special method Honeybadger checks for when any exception is reported:

Faraday::ClientError.class_eval do
  def to_honeybadger_context
    {
      response_status:  err.response.status,
      response_headers: err.response.headers
    }
  end
end

By adding the #to_honeybadger_context method to Faraday::ClientError, we'll get the response context whenever that error occurs, without cluttering up our code!

What to do next:
  1. Try Honeybadger for FREE
    Honeybadger helps you find and fix errors before your users can even report them. Get set up in minutes and check monitoring off your to-do list.
    Start free trial
    Easy 5-minute setup — No credit card required
  2. Get the Honeybadger newsletter
    Each month we share news, best practices, and stories from the DevOps & monitoring community—exclusively for developers like you.
    author photo

    Joshua Wood

    Josh is Honeybadger's resident bug hunter and technical debt collector. Once enthusiastically referred to as a "human exception tracker", he spends his days crafting the middleware, plugins, and gems which keep the 'badger fat and happy through a steady diet of fresh data.

    More articles by Joshua Wood
    Stop wasting time manually checking logs for errors!

    Try the only application health monitoring tool that allows you to track application errors, uptime, and cron jobs in one simple platform.

    • Know when critical errors occur, and which customers are affected.
    • Respond instantly when your systems go down.
    • Improve the health of your systems over time.
    • Fix problems before your customers can report them!

    As developers ourselves, we hated wasting time tracking down errors—so we built the system we always wanted.

    Honeybadger tracks everything you need and nothing you don't, creating one simple solution to keep your application running and error free so you can do what you do best—release new code. Try it free and see for yourself.

    Start free trial
    Simple 5-minute setup — No credit card required

    Learn more

    "We've looked at a lot of error management systems. Honeybadger is head and shoulders above the rest and somehow gets better with every new release."
    — Michael Smith, Cofounder & CTO of YvesBlue

    Honeybadger is trusted by top companies like:

    “Everyone is in love with Honeybadger ... the UI is spot on.”
    Molly Struve, Sr. Site Reliability Engineer, Netflix
    Start free trial