In a Rails 8.1 app, how do you write and register an error subscriber that forwards Rails.error reports to an error tracker?
answer
- any object that responds to report
- keywords: handled, severity, context, source
- Rails.error.subscribe in an initializer
- a subscriber must never raise
- filter on source; add_middleware is 8.1
basics
~20 sWrite 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.
solid answer
~40 sA subscriber is any object with `report(error, handled:, severity:, context:, source:)`; `Rails.error.subscribe` raises `ArgumentError` for one without it. Register it once, in `config/initializers/` or a gem's Railtie initializer; subscribers are called in registration order, on the thread that reported. Inside, map `severity` and `handled` to the tracker's levels, send `context`, and use `source` to skip noise you do not want, such as reports from a library you do not care about. The method must not raise: in production the reporter logs a crashing subscriber at fatal and moves on, but in development and test it re-raises. Keep it fast, because it runs inline in the request. `Rails.error.unsubscribe` removes a gem's subscriber, `disable` silences one for a block, and Rails 8.1's `add_middleware` computes shared context entries for every subscriber.
code
ruby · 15 linesmodule MapErrors
class Railtie < ::Rails::Railtie
initializer "map_errors.subscribe" do
Rails.error.subscribe(MapErrors::Subscriber.new)
end
end
class Subscriber
def report(error, handled:, severity:, context:, source:)
MapErrors.client.enqueue(error, severity:, handled:, listing_id: context[:listing_id])
rescue => e
warn "map_errors subscriber failed: #{e.class}"
end
end
endgo deeper
Know that a subscriber is an object with a report method, registered with Rails.error.subscribe, and that it is how reports reach a tracker.
Explain the five-argument report signature, registration order, and how unsubscribe and disable remove or silence a gem's subscriber.
Build a subscriber that never raises, stays off the request's critical path, filters by source, strips live objects from context and is tested with assert_error_reported.
Weigh one in-house subscriber against vendor auto-registration, and decide which sources and severities page someone versus land in a weekly review.
## The contract `Rails.error` (an `ActiveSupport::ErrorReporter`) delivers each report to its **subscribers**. Rails does not ship one: a new app's reporter has an empty list, and reports go nowhere until something subscribes. Many tracker SDKs register a subscriber automatically from their Railtie; when yours does not, or you need your own rules, you write one. The contract is duck-typed: - the object must respond to `report`; - `report` receives the exception plus four keywords: **`handled:`** (Boolean), **`severity:`** (`:error`, `:warning` or `:info`), **`context:`** (a Hash) and **`source:`** (a String); - `report` **should never raise**. ```ruby # config/initializers/error_subscriber.rb class TrackerSubscriber IGNORED_SOURCES = %w[active_record.connection_pool].freeze def report(error, handled:, severity:, context:, source:) return if IGNORED_SOURCES.include?(source) ErrorTracker.notify(error, level: severity, unhandled: !handled, tags: { source: source }, extra: context.except(:controller, :job)) end end Rails.error.subscribe(TrackerSubscriber.new) ``` `ErrorTracker` here stands for whatever client your tracker provides; the shape of the subscriber does not depend on it. ## Registration 1. **Where**: an initializer for app code; a Railtie `initializer` block for a gem. Registration is process-wide and happens once at boot. 2. **Order**: subscribers run in the order they were registered, synchronously, on the thread that made the report. 3. **Validation**: `subscribe` raises `ArgumentError` if the object has no `report` method. 4. **Removal**: `Rails.error.unsubscribe(subscriber_or_class)` removes one, useful to drop a subscriber a gem added; `Rails.error.disable(subscriber_or_class) { ... }` skips it only for the block. ## Writing it well | Concern | What to do | Why | |---|---|---| | Failure | rescue inside `report` or keep it trivial | a raising subscriber is re-raised in development and test | | Latency | hand off to the SDK's async sender | the subscriber runs inline, inside the request or job | | Noise | filter on `source` and `severity` | Rails and libraries report with their own sources | | Payload | send ids from `context`, drop live objects | Rails puts the controller and job instances in `context` | | Duplicates | rely on Rails' marking | an exception is reported once even if re-raised | When a subscriber does raise, what happens depends on the reporter's `logger`. At boot, Rails gives the reporter `Rails.logger` when `config.consider_all_requests_local` is false (production): the failure is logged at `fatal` and the remaining subscribers still run. When it is true (development, test) there is no logger and the subscriber's exception propagates, so you find the bug early. ## Shared context with middleware (Rails 8.1) Rails 8.1 added **`Rails.error.add_middleware`**. A middleware is a callable that receives the error and the same keywords as `report`, and returns the context hash; it runs before the subscribers, so all of them see its result: ```ruby Rails.error.add_middleware(->(error, context:, **) { context.merge(release: ENV["APP_RELEASE"]) }) ``` Before 8.1 each subscriber had to compute such entries itself. ## Testing the subscriber Unit-test `report` directly with a fake client. For code that should report, `ActiveSupport::TestCase` includes `assert_error_reported(ErrorClass) { ... }`, `assert_no_error_reported`, and, new in 8.1, `capture_error_reports`, which return the captured reports for checking `handled`, `severity` and `context`. ## Deciding what to forward Not every report deserves the same treatment. Reports arrive from your own code (`source: "application"`), from Rails' wrappers (`"application.action_dispatch"`, `"application.active_job"`) and from libraries such as the cache stores, which report a failing cache backend as a handled warning. A practical policy: 1. Forward everything with `handled: false`; those are failures nobody recovered from. 2. Forward handled `:warning` reports, but tag them so the tracker can group them away from crashes. 3. Drop or sample `:info` reports, which are usually there for curiosity rather than action. 4. Keep an explicit list of sources you ignore, reviewed when you upgrade Rails or a gem. ## What a subscriber does not do - It does not catch errors: unhandled errors reach it because Rails' request and job wrappers report them. - It does not decide whether the app continues: that was settled by `handle`, `record` or the wrapper before the subscriber runs. - It does not receive `ActiveSupport::Notifications` events; those go to instrumentation subscribers.
- A tracker gem auto-registers a subscriber, but you want only your own. How do you remove it?Call `Rails.error.unsubscribe` with the gem's subscriber class (or the instance) in an initializer that runs after the gem's Railtie. `unsubscribe` accepts either, matching with `===`. To silence it only around one block, use `Rails.error.disable(ThatClass) { ... }` instead.
- What happens in production if your subscriber's report method raises?Rails rescues it. Because `consider_all_requests_local` is false, the reporter's `logger` is `Rails.logger`; it logs the subscriber's error at `fatal` with its backtrace and continues with the remaining subscribers. In development and test there is no logger, so the error is re-raised.
- How do you assert in a Rails test that a block reported a GeocodingClient::Error?`assert_error_reported(GeocodingClient::Error) { ... }` from `ActiveSupport::TestCase` fails if no matching report was made and returns the report, so you can check `report.handled?`, `report.severity` and `report.context`. `assert_no_error_reported` checks the opposite.
- A subscriber must inherit from an ActiveSupport base class.
- Rails registers a default subscriber that logs every report.
- A subscriber that raises is always silently ignored, in every environment.
- Subscribers run asynchronously in a background thread by default.
- An error subscriber also receives every ActiveSupport::Notifications event.
Assumes Rails 8.1: Rails.error.add_middleware and the capture_error_reports test helper were added in 8.1.0; the subscriber contract itself is unchanged.