skip to content

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%

answer

  1. for 'this should never happen'
  2. accepts a String or an exception
  3. debug_mode follows consider_all_requests_local
  4. UnexpectedError inherits from Exception
  5. production: report as :warning, return nil

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.

solid answer

~40 s

`Rails.error.unexpected(error_or_message)` is for preconditions that should never fail but that production can survive, such as a listing reaching the map without an address. A String becomes a `RuntimeError`. Its behaviour depends on `Rails.error.debug_mode`, which Rails sets to `true` at boot when `config.consider_all_requests_local` is true, the generated setting for development and test. In debug mode it raises `ActiveSupport::ErrorReporter::UnexpectedError` with the original as its `cause`; that class inherits from `Exception`, so an ordinary `rescue => e` higher up cannot hide it and the developer sees it. With debug mode off, as in production, it reports the error with `handled: true` and `severity: :warning` (overridable) and returns `nil`, so your code continues to its graceful path.

code

ruby · 9 lines
ruby
result = Rails.error.unexpected("listing 42 has no address")

# consider_all_requests_local = true (development, test):
#   raises ActiveSupport::ErrorReporter::UnexpectedError,
#   "RuntimeError: listing 42 has no address", cause: the RuntimeError

# consider_all_requests_local = false (production):
#   subscribers get the RuntimeError with handled: true, severity: :warning
#   result # => nil

go deeper

for a junior

Know that unexpected is for situations that should never happen: it raises while you develop and test, and only reports in production.

for a middle

Explain that debug_mode follows consider_all_requests_local, that a String becomes a RuntimeError, and why UnexpectedError subclasses Exception.

for a senior

Use unexpected only for invariants with a graceful production path, keep expected failures on handle, and watch for staging configs that flip the behaviour.

for a principal

Decide how the team treats invariant violations: which may degrade with a report and which must fail hard, and how those warnings get triaged.

## The case it was built for Some code paths are bugs if they ever run, yet the app can recover from them. A listing published without an address should be impossible, but if one slips through, the map page can still render without its pin. Two bad options existed before: - **Raise**: correct in development, where you want to notice, but it breaks the page for users in production. - **Log or report quietly**: safe in production, but in development the bug is easy to miss. `Rails.error.unexpected` does both, chosen by environment: loud while developing and testing, quiet but reported in production. ## What it does ```ruby def map_pin if address.blank? Rails.error.unexpected("[BUG] listing #{id} published without an address") return city_centroid end GeocodingClient.lookup(address) end ``` 1. If you pass a **String**, it is wrapped in a `RuntimeError`. Unlike `Rails.error.report`, which rejects a String with `ArgumentError`, `unexpected` accepts a message or an exception. 2. If **`debug_mode`** is true, Rails raises **`ActiveSupport::ErrorReporter::UnexpectedError`**, with a message built from the original class and message, the original backtrace, and the original error as its `cause`. 3. Otherwise it calls `report` with `handled: true` and `severity: :warning` (both `severity:` and `context:` can be passed) and returns `nil`, so the next line, here `return city_centroid`, runs. ## Where `debug_mode` comes from `debug_mode` is an attribute on the reporter. A Rails initializer sets it at boot: | `config.consider_all_requests_local` | Generated in | Reporter behaviour | |---|---|---| | `true` | `development.rb`, `test.rb` | `debug_mode = true`: `unexpected` raises | | `false` | `production.rb` | `logger = Rails.logger`: `unexpected` reports | So the switch is that config value, not the environment's name. A staging environment copied from production behaves like production; a production box temporarily set to show detailed errors would start raising. The same initializer explains a second difference: when debug mode is off, the reporter is given `Rails.logger`, which it uses only to log a subscriber that itself crashed. In debug mode there is no logger, so a crashing subscriber's exception propagates. ## Why `UnexpectedError` inherits from `Exception` Ruby's bare `rescue` and `rescue => e` catch only `StandardError` and its subclasses. `UnexpectedError` is defined as `Class.new(Exception)`, outside that tree, so: - a `rescue => e` in a service object, a `Rails.error.handle` block, or a `rescue_from StandardError` handler will **not** catch it; - it travels up to the development error page or fails the test; - the developer sees the broken assumption instead of a silent fallback. This is also why you should not rescue `Exception` around such code: you would defeat the mechanism. ## How it compares with the other reporter calls | Call | Takes | Raises afterwards? | `handled:` | Default `severity:` | |---|---|---|---|---| | `Rails.error.report` | an exception | no | `true` | `:warning` | | `Rails.error.handle` | a block | no, swallows | `true` | `:warning` | | `Rails.error.record` | a block | yes, the same error | `false` | `:error` | | `Rails.error.unexpected` | an exception or a String | only in debug mode, as `UnexpectedError` | `true` | `:warning` | `unexpected` is the only one whose behaviour changes with the environment, and the only one that accepts a plain message. ## When to use it, and when not - **Use it** for invariants your own code is supposed to guarantee, where production has a sensible way to continue. - **Do not use it** for failures you expect sometimes, such as a geocoding timeout; those are `Rails.error.handle` with a fallback. - **Do not use it** for conditions that must stop the request in every environment; raise a normal error. In tests, this behaviour is a feature: because `test.rb` sets `consider_all_requests_local = true`, a code path that hits `unexpected` fails the test run instead of passing with a hidden fallback.

  • Would a rescue_from StandardError handler in ApplicationController stop the error Rails.error.unexpected raises in development?
    No. `ActiveSupport::ErrorReporter::UnexpectedError` inherits from `Exception`, not `StandardError`, so a handler registered for `StandardError` does not match it. It reaches the development error page, which is the point: a broken assumption should not be absorbed while you are developing.

  • Rails.error.unexpected raises in production as well, after reporting.
  • debug_mode is switched on by Rails.env.development? alone.
  • A bare rescue => e catches the error unexpected raises in development.
  • unexpected only accepts an exception, like Rails.error.report.
  • In production, unexpected reports with handled: false and severity :error.