skip to content

In a Rails controller, how do Rails.error.set_context and the context: option attach details such as the current user to error reports?

level: middleimportance: should knowfreq 25%

answer

  1. per-execution store, not a global
  2. set in a before_action
  3. context: merged over set_context
  4. same key: the per-call value wins
  5. :controller and :job added by Rails

basics

~20 s

Rails.error.set_context stores key-value pairs for the current request or job; every later report merges them with its own context: hash, the call's keys winning, and passes the result to subscribers. Rails clears the store when the execution ends.

solid answer

~40 s

`Rails.error.set_context(user_id: Current.user&.id, listing_id: params[:id])` writes into `ActiveSupport::ExecutionContext`, a store scoped to the current execution. The executor starts each request or job with a fresh store and drops it when that execution completes, so values never leak into the next request. When any report happens, through `report`, `handle`, `record` or Rails' own wrappers, the reporter takes that store, merges the call's `context:` hash over it (the call's value wins on a shared key) and hands the result to every subscriber as `context:`. Rails adds two entries itself: `:controller`, the controller instance processing the action, and `:job`, the Active Job instance being performed. Set request-wide values once in a `before_action`; pass one-off details with `context:`.

code

ruby · 12 lines
ruby
class ListingsController < ApplicationController
  before_action { Rails.error.set_context(listing_id: params[:id]) }

  def map
    @listing = Listing.find(params[:id])
    @pin = Rails.error.handle(GeocodingClient::Error,
                              fallback: -> { @listing.city_centroid },
                              context: { provider: GeocodingClient.provider_name }) do
      GeocodingClient.lookup(@listing.address)
    end
  end
end

go deeper

for a junior

Recall that set_context attaches details to every later error report in the same request, and that context: adds details to one report.

for a middle

Explain the merge order (call-site keys win), that the store lives for one request or job, and that Rails adds :controller and :job entries.

for a senior

Set request-wide context once after authentication, keep personal data and heavy objects out of it, and check that unhandled errors carry it too.

for a principal

Agree a small, stable context schema across services so tracker searches work everywhere, and decide what user data may leave the system at all.

## The problem context solves An exception class and a backtrace tell you *where* a failure happened, not *for whom*. On a property-search site, a geocoding timeout matters differently if it hit one listing once or every listing for one agency. Error trackers group and filter by attached details, so the app needs a way to attach them without threading a hash through every method that might fail. `ActiveSupport::ErrorReporter` (the object behind `Rails.error`) offers two layers: | Layer | Set with | Lifetime | Typical content | |---|---|---|---| | Execution context | `Rails.error.set_context(...)` | the current request or job | user id, account, request id | | Per-report context | `context:` on `report`, `handle`, `record`, `unexpected` | that one report | the listing id, the provider called | ## How `set_context` stores values `set_context` is a thin call into `ActiveSupport::ExecutionContext.set`. That store is **per execution**, not a global: 1. When Rails starts an execution (an HTTP request through the `ActionDispatch::Executor` middleware, an Active Job, a `bin/rails runner` script), the executor starts a fresh, empty store. 2. Code during that execution adds keys with `set_context`. 3. When the execution completes, the executor drops the store, so nothing set for one request is visible in the next, even on the same Puma thread. Rails fills two keys on its own: **`:controller`** is set to the controller instance when an action is processed, and **`:job`** to the job instance when a job performs. A subscriber can read the controller's `request` or the job's arguments from them. A block form exists too: `Rails.error.set_context(provider: "backup") { ... }` sets the keys for the block and restores their previous values afterwards. ## How a report assembles the final context On every report the reporter: - copies the execution context into a hash; - **merges the call's `context:` over it**, so a key passed at the call site replaces the same key from `set_context`; - passes the result through any context middleware registered with `Rails.error.add_middleware` (Rails 8.1); - calls each subscriber with that hash as `context:`. ```ruby Rails.error.set_context(agency_id: 7, listing_id: nil) Rails.error.handle(context: { listing_id: 42 }) { raise GeocodingClient::Error } # subscribers receive context: { agency_id: 7, listing_id: 42, ... } ``` ## Where to set it Request-wide values belong in a `before_action` in `ApplicationController`, after authentication has run: ```ruby class ApplicationController < ActionController::Base before_action :set_error_context private def set_error_context Rails.error.set_context(user_id: Current.user&.id, agency_id: Current.user&.agency_id) end end ``` Errors raised later in the action, including unhandled ones that Rails' request wrapper reports, carry those keys, because the wrapper reports before the execution context is cleared. ## Execution context and `Current` attributes Apps generated with the authentication generator already keep the signed-in session in `Current`, an `ActiveSupport::CurrentAttributes` subclass. Both stores are reset by the same executor at the end of each request or job, so they line up naturally: read from `Current` after authentication and copy the ids into `set_context`. They are still separate stores; a subscriber sees only what reached the error context, not every `Current` attribute. | Store | Reset by | Read by | |---|---|---| | `ActiveSupport::CurrentAttributes` (`Current.user`) | the executor, per execution | your application code | | Error execution context (`set_context`) | the executor, per execution | every error subscriber | ## Pitfalls - **Personal data**: context goes to a third-party service. Send ids, not email addresses or addresses typed by users, unless your privacy policy covers it. - **Heavy objects**: a subscriber may serialise the whole hash; pass scalars rather than Active Record objects. - **Confusing it with `Rails.event.set_context`**: the structured event reporter has its own context store, and values set there do not appear in error reports. - **Assuming it is global**: setting context at boot or in an initializer does not carry into requests, because each execution starts empty. The result is that application code only ever adds what it uniquely knows, and the tracker still receives a complete picture of who was affected.

  • If a before_action calls Rails.error.set_context(user_id: 1) and a later report passes context: { user_id: 2 }, which value reaches the subscriber?
    `2`. The reporter starts from the execution context and merges the call's `context:` hash over it, so a key given at the call site replaces the same key from `set_context`. Other keys from `set_context` are kept.
  • Why does a value set with Rails.error.set_context not show up in the next request on the same Puma thread?
    Because the store is per execution. The application executor, which wraps each request and job, starts a fresh execution context when the work begins and drops it when the work completes. Nothing set during one request survives into the next.

  • Rails.error.set_context sets a global hash that persists across requests.
  • The set_context value wins over the context: hash passed at the call site.
  • Rails.event.set_context and Rails.error.set_context share one store.
  • context: replaces the execution context instead of being merged over it.
  • Rails adds nothing to the context, so the controller is never available to subscribers.