How to add context data to exceptions in Ruby

Sometimes the standard backtrace / error message combo isn't enough. Sometimes you need extra data to locate the cause of an error. Fortunately, it's super easy to do in Ruby.

Customizing the error message

The simplest way to add contextual information to your errors is to add it to the exception's message. In the example below I'm catching an exception and re-raising it with a new message:

  raise "foo"
rescue => e
  raise e.class, "bar"

# RuntimeError: bar

A good use case for this approach might be when you're rendering a template. Any exception that happens inside the template doesn't know the template's filename. But that's pretty important information for you to know when debugging.

Here's an example of how you could rescue template errors and prepend the file name to the message.

filename = "mytemplate.erb"
template = # Contains "<% 1/0 %>"

e = 

rescue => e
  raise e.class, [filename, e.message].join(": ")

# ZeroDivisionError: mytemplate.erb: divided by 0

Wrapping the exception

Another option for including contextual information in exceptions is to create a custom exception. Since exceptions are just classes like everything else in Ruby, you can add as many attr_accessors as your heart desires.

Here's how that might look:

TemplateError < StandardError
  attr_reader :filename

  def initialize(msg, filename)
    @filename = filename

rescue => e
  raise, filename)

Using Honeybadger's context feature

Ok, ok. I had to put this in, since Honeybadger has a pretty slick way to add contextual information to your exceptions. Instead of modifying the exception object, you simply use the Honeybadger.context method from anywhere in your application.

class ApplicationController


  def find_current_user
    user = ...
    Honeybadger.context(user_id:, user_email:, user.scope: "user")


When an exception happens, the context data is reported along with it. You can then view the data along with other exception data in our web or mobile apps.

Honeybadger's context feature lets you attach whatever info you need to your exceptions without much code. Honeybadger's context feature lets you attach whatever info you need to your exceptions without much code.

Level up your software development career

Join our community of kick-ass developers as we learn engineering, DevOps, cloud architecture, and bootstrapping remote software companies. Tell me more →

We're Honeybadger. We'll never send you spam; we will send you cool shit like exclusive content, memes, and special swag.