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. In this post we'll discuss three easy ways to add more context to your exceptions.

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:

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

# 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 = File.read(filename) # Contains "<% 1/0 %>"

e = ERB.new(template) 

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

# 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
    super(msg)
  end
end

begin
  ERB.new(template).result
rescue => e
  raise TemplateError.new(e.message, filename)
end

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.id, user_email: user.email, user.scope: "user")
  end

end

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.

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

    Starr Horne

    Starr Horne is a Rubyist and Chief JavaScripter at Honeybadger.io. When she's not neck-deep in other people's bugs, she enjoys making furniture with traditional hand-tools, reading history and brewing beer in her garage in Seattle.

    More articles by Starr Horne
    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: