In Rails, how do Rails.error.handle and Rails.error.record differ in what they report, return and re-raise when the block fails?
answer
- swallow versus re-raise
- handle: handled true, severity warning
- record: handled false, severity error
- fallback: callable, else nil
- only StandardError unless classes listed
basics
~20 sRails.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.
solid answer
~40 sBoth wrap a block and rescue `StandardError`, or only the classes you pass as positional arguments. `Rails.error.handle` reports the error with `handled: true` and `severity: :warning`, swallows it, and returns `fallback.call` if you gave `fallback:` or `nil` otherwise, so the caller carries on: a map pin falls back to the city centre when geocoding times out. `Rails.error.record` reports with `handled: false` and `severity: :error`, then re-raises the same exception, so the caller still fails: right for a job that must be retried. With no error, both return the block's value. Errors outside the listed classes pass straight through, unreported by that call. Both take `severity:`, `context:` and `source:`; only `handle` takes `fallback:`.
code
ruby · 9 linespin = Rails.error.handle(GeocodingClient::Error, fallback: -> { listing.city_centroid }) do
GeocodingClient.lookup(listing.address)
end
# lookup succeeds -> its coordinates
# GeocodingClient::Error -> reported (handled: true, :warning), city centroid returned
# NoMethodError -> not rescued here; propagates unreported by this call
Rails.error.record { listing.update!(coordinates: pin) }
# ActiveRecord::RecordInvalid -> reported (handled: false, :error), then re-raisedgo deeper
Remember the one-word split: handle swallows, record re-raises. Know that both return the block's value when nothing fails.
Explain the handled and severity values each sends, what handle returns with and without fallback:, and how listing classes narrows what gets rescued and reported.
Show where each belongs: handle with a real fallback for degradable features, record where work must fail and retry, and narrow class lists so bugs are not swallowed.
Set conventions for when degrading is acceptable and how swallowed warnings are reviewed, so handle does not become a way to hide failing integrations.
## Two block wrappers around one reporter `Rails.error` is the app's `ActiveSupport::ErrorReporter`. Besides the manual `report` call it offers two **block wrappers** that combine a rescue with a report. They differ in one decision: after the failure is reported, does the program continue or not? | | `Rails.error.handle` | `Rails.error.record` | |---|---|---| | After reporting | **swallows** the error | **re-raises** the error | | `handled:` sent | `true` | `false` | | Default `severity:` | `:warning` | `:error` | | Return value on failure | `fallback.call`, or `nil` | none: the exception propagates | | Return value on success | the block's value | the block's value | | Accepts `fallback:` | yes | no | ## `handle`: report and carry on Use `handle` when the feature can degrade instead of failing. On a property map, a listing whose address the geocoding service cannot resolve should still appear, pinned at its city's centre, rather than taking the whole page down: ```ruby coordinates = Rails.error.handle(GeocodingClient::Error, Net::OpenTimeout, fallback: -> { listing.city_centroid }, context: { listing_id: listing.id }) do GeocodingClient.lookup(listing.address) end ``` - If `lookup` succeeds, `coordinates` is its return value. - If it raises one of the listed classes, the reporter tells every subscriber (`handled: true`, `severity: :warning`), then calls the **fallback** with no arguments and returns its result. - Without `fallback:`, the failed call returns `nil`, so the caller must cope with `nil`. ## `record`: report and fail anyway Use `record` when the caller must still see the failure, but you want the report made at this point, with this context, instead of relying on whatever catches it later: ```ruby class GeocodeListingJob < ApplicationJob def perform(listing) Rails.error.record(context: { listing_id: listing.id }) do listing.update!(coordinates: GeocodingClient.lookup(listing.address)) end end end ``` The error is reported with `handled: false` and `severity: :error`, then raised again, so the job still fails and its retry rules still apply. Because Rails marks a reported exception, the job runner's own report of the same exception further up is skipped: the tracker sees it once, with the listing id attached. ## Narrowing what is rescued Both methods rescue `StandardError` when no classes are given. Passing classes narrows the rescue: 1. An error of a listed class (or a subclass) is reported and then swallowed or re-raised. 2. Any other error is **not rescued by that call at all**: it is neither reported by it nor swallowed, and it propagates as if the wrapper were not there. 3. Exceptions outside `StandardError`, such as `Interrupt`, are never caught by the default list. Narrowing matters most for `handle`. A bare `Rails.error.handle { ... }` around a geocoding call also swallows a `NoMethodError` from a typo, turning a bug into a quiet warning; listing `GeocodingClient::Error` and `Net::OpenTimeout` keeps bugs loud. ## Options both accept - **`severity:`** overrides the default (`:error`, `:warning` or `:info`). - **`context:`** adds details for this report, merged over anything set with `Rails.error.set_context`. - **`source:`** names the reporting layer, default `"application"`. ## Mistakes that bite - **A value instead of a callable**: `fallback: listing.city_centroid` evaluates the centroid even when nothing fails, and when something does, `handle` calls `.call` on it; unless the value happens to respond to `call`, that raises `NoMethodError` from inside the rescue. Always pass a lambda or proc. - **Using the return value without a fallback**: with no `fallback:`, a failed `handle` returns `nil`, and the next line that does `pin.latitude` raises `NoMethodError` anyway. - **Wrapping too much**: a `handle` block around a whole action body swallows every `StandardError` inside it, including validation and authorization failures you meant to surface. - **Expecting `record` to retry**: it only reports and re-raises; retries come from whoever catches the error, such as the job's own retry rules. ## Choosing between them - The user can still get a useful answer without this result: **`handle`**, with a `fallback:` that produces that answer. - The work must not be considered done: **`record`**, so a job retries or a request fails, with the report already made. - A rescue already exists for other reasons: neither; call **`Rails.error.report`** inside it. A common mistake is reaching for `handle` everywhere because it keeps things running. A swallowed error the tracker files as a warning is easy to ignore; failures that should stop the work belong in `record`.
- Why is a bare Rails.error.handle block around a third-party call risky?With no classes it rescues every `StandardError`, including `NoMethodError` or `NameError` from a bug in your own code. Those get reported as handled warnings and swallowed, so the page keeps working with a fallback while the bug hides in a low-priority tracker bucket. List the service's error classes so programming errors still raise.
- When would you use Rails.error.record inside a job instead of letting the error escape on its own?When the report needs details only that spot knows, such as the listing id or the geocoding provider. `record` sends them with `handled: false` and re-raises, so the job still fails and retries; the exception is marked as reported, so the job runner does not report it a second time without that context.
- Rails.error.handle re-raises the error after reporting it.
- Rails.error.record swallows the error and returns nil.
- fallback: is a plain value, not a callable.
- Listing error classes still reports every other StandardError too.
- Rails.error.handle reports with severity :error and handled: false.
- Rails.error.record accepts fallback: just like handle.