skip to content

Reporter API & Subscribers

Rails.error is one place to report exceptions: handle and record wrap blocks, report sends one, and subscribers forward them to a tracker. Interviewers ask how unhandled errors reach it.

part ofRuby on Railsread it →
on this pageshow

explore

questions

6

In a Rails app, what does Rails.error.report do with an exception you rescued, and what do its handled: and severity: options default to?

level: juniorimportance: must knowfreq 40%

answer

  1. one call, every subscriber
  2. an Exception instance, not a String
  3. handled: true unless you say otherwise
  4. severity follows handled: :warning or :error
  5. returns nil and does not re-raise

basics

~10 s

Rails.error.report(error) hands an exception you already rescued to every registered error subscriber, then returns nil without re-raising it. handled: defaults to true, and severity: defaults to :warning when handled, :error when handled: false.

solid answer

~40 s

`Rails.error` is the app's `ActiveSupport::ErrorReporter`, and `report` is its lowest-level call: you pass an `Exception` instance and it calls `report` on every subscriber with `handled:`, `severity:`, `context:` and `source:`. It never re-raises the error, so the code after it keeps running, and it returns `nil`. `handled:` defaults to `true`; `severity:` defaults to `:warning` when handled and `:error` when you pass `handled: false`, and only `:error`, `:warning` or `:info` are accepted. `source:` defaults to `"application"` and `context:` is merged over the execution context. Passing a String raises `ArgumentError` (that is what `Rails.error.unexpected` is for). A new app registers no subscriber, so until a tracker gem or your own subscriber is added a report is delivered to nobody.

code

ruby · 8 lines
ruby
def refresh_pins(listings)
  listings.each do |listing|
    listing.update!(coordinates: GeocodingClient.lookup(listing.address))
  rescue GeocodingClient::Error, Net::ReadTimeout => error
    # handled: true, severity: :warning, source: "application"
    Rails.error.report(error, context: { listing_id: listing.id })
  end
end

go deeper

for a junior

Recall that report takes a rescued Exception, passes it to every subscriber and returns nil without re-raising. Know the defaults: handled true, severity warning.

for a middle

Explain how severity follows handled when you omit it, why a String is rejected, and why a fresh app's reports go nowhere until a subscriber is registered.

for a senior

Show you use report only where a rescue already exists, rely on the reported-once marking when re-raising, and pick handled and severity so the tracker's alerting means something.

for a principal

Argue for one reporting vocabulary across the codebase so the tracker stays a swappable detail, and set team rules on what counts as handled versus a warning.

## What `Rails.error` is `Rails.error` returns the application's single **error reporter**, an instance of `ActiveSupport::ErrorReporter`. It is not an error tracker: it stores nothing and sends nothing over the network. It is a fan-out point. Code that wants an error recorded calls the reporter, and the reporter calls every **subscriber** that has registered with it, one after another. A subscriber is any object with a `report` method, usually supplied by an error-tracking SDK or written by you. The point of the indirection is that application code says *what* happened once, in one vocabulary, and the choice of tracker lives in one place. Swapping trackers, adding a second one, or silencing one in tests does not touch the code that reports. ## The `report` call `report` is the manual entry point, for an exception you have already rescued yourself: ```ruby class MapPinsController < ApplicationController def show @listing = Listing.find(params[:id]) @coordinates = GeocodingClient.lookup(@listing.address) rescue GeocodingClient::Error => error Rails.error.report(error, context: { listing_id: @listing.id }) @coordinates = @listing.city_centroid end end ``` What happens inside, in order: 1. If this exception object was already reported (Rails marks it, and every exception in its `cause` chain, after a report), the call returns at once. One failure is never sent twice. 2. The argument must be an `Exception`; anything else raises `ArgumentError`. 3. If the exception was built with `.new` and never raised, Rails gives it a backtrace. 4. `severity:` is checked against `:error`, `:warning` and `:info`; anything else raises `ArgumentError`. 5. The context is assembled, then each subscriber's `report` is called with the error and the four options. 6. The method returns `nil`. It **does not re-raise**: the line after it runs. ## The options and their defaults | Option | Default | What it tells a subscriber | |---|---|---| | `handled:` | `true` | whether the app recovered from the error | | `severity:` | `:warning` if handled, `:error` if not | how loud the report should be | | `context:` | `{}` | extra details, merged over `set_context` values | | `source:` | `"application"` | which library or layer reported it | - **`handled:`** is a statement, not a switch. `report` behaves the same either way; the flag tells the tracker whether a user was affected. Rails' own request and job wrappers pass `handled: false` for errors nobody caught. - **`severity:`** is derived from `handled:` unless you pass it. `Rails.error.report(error, handled: false)` is therefore reported as `:error` without saying so. - **`source:`** lets subscribers filter: Rails itself reports with sources such as `"application.action_dispatch"` or `"application.active_job"`. ## What `report` is not - It is **not logging**. The reporter writes nothing to `Rails.logger` for a report; its own `logger` is only used, in production, to record a subscriber that crashed. - It is **not delivered anywhere by default**. `rails new` registers no subscriber, so in a fresh app a report reaches nobody until a tracker gem or your initializer subscribes one. - It is **not a rescue**. It does not catch anything; use `Rails.error.handle` or `Rails.error.record` when you want the reporter to wrap a block. - It does **not accept a String**. For "this should never happen" messages there is `Rails.error.unexpected`, which builds the exception for you. ## `report` against the older habits | Approach | Tracker coupling | Context and filtering | |---|---|---| | `rescue` + `Rails.logger.error` | none, but nothing alerts | only what you format into the line | | `rescue` + the tracker client called directly | every call site names the vendor | per call site, inconsistent | | `rescue` + `Rails.error.report` | one subscriber names the vendor | shared `set_context`, `source:`, severity | The last row is also what Rails itself uses: the request and job wrappers, the cache stores and Active Record report through the same object, so your manual reports and the framework's land side by side. ## When to reach for it Use `report` when the rescue already exists for another reason: a `rescue` clause that falls back to a default, a loop that skips one bad row and carries on, or a `rescue_from` handler that renders a friendly page but should still tell the tracker. When you are writing a new rescue only so you can report, `handle` (swallow) or `record` (re-raise) says the same thing in less code and sets `handled:` for you. A last detail that matters in practice: because reported exceptions are marked, calling `report` in a rescue and then re-raising does not produce a second report when Rails' request wrapper sees the same exception further up. That is the guard that keeps one geocoding timeout from showing up twice on the tracker's dashboard.

  • What happens if you call Rails.error.report(error, severity: :fatal)?
    It raises `ArgumentError`. The reporter accepts only `:error`, `:warning` and `:info`, the values in `ActiveSupport::ErrorReporter::SEVERITIES`. `:fatal` is a Logger level, not an error-reporter severity, so it is rejected before any subscriber is called.
  • If a rescue clause reports an error and then re-raises it, does the tracker get two reports when Rails' request wrapper sees it?
    No. After a report Rails marks the exception, and each exception in its `cause` chain, as reported; a later `report` of the same object returns immediately. The request wrapper's own report of the re-raised exception is skipped, so the failure appears once.

  • Rails.error.report writes the exception to Rails.logger by default.
  • Rails.error.report re-raises the exception after the subscribers run.
  • handled: defaults to false, so a manual report counts as unhandled.
  • You can pass a message String to Rails.error.report instead of an exception.
  • A new Rails app ships with a subscriber that sends reports somewhere.
  • severity: accepts any Logger level, including :fatal and :debug.
open as a page

In Rails, how do Rails.error.handle and Rails.error.record differ in what they report, return and re-raise when the block fails?

level: middleimportance: must knowfreq 45%

basics

~20 s

Rails.error.handle reports a failure as handled with severity :warning, swallows it and returns nil or fallback.call. Rails.error.record reports it as unhandled with severity :error and re-raises it. Both return the block's value when nothing fails.

open as a page

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%

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.

open as a page

In a Rails 8.1 app, how do you write and register an error subscriber that forwards Rails.error reports to an error tracker?

level: seniorimportance: should knowfreq 35%

basics

~20 s

Write an object whose report(error, handled:, severity:, context:, source:) method calls the tracker's client, and register it with Rails.error.subscribe in an initializer. Every report, manual or from Rails' request and job wrappers, then reaches the tracker.

open as a page

In a Rails 8.1 app with no rescue code of your own, how does an exception raised in a controller action or an Active Job reach Rails.error subscribers?

level: seniorimportance: should knowfreq 30%

basics

~20 s

Rails runs every request and job inside its executor. ActionDispatch::Executor reports an escaping request error with handled: false, and the executor around each job reports whatever perform lets escape. rescue_responses classes, such as 404s, are skipped.

open as a page

In Rails, what does Rails.error.unexpected do, and why does the same call raise in development but only report in production?

level: middleimportance: nice to knowfreq 15%

basics

~10 s

Rails.error.unexpected flags a broken assumption. With debug_mode on (consider_all_requests_local, so development and test) it raises ActiveSupport::ErrorReporter::UnexpectedError; otherwise it reports the error as handled with severity :warning and returns nil.

open as a page