skip to content

In Rails, when would you map an exception in config.action_dispatch.rescue_responses instead of handling it with rescue_from?

level: seniorimportance: should knowfreq 30%

answer

  1. middleware layer vs controller layer
  2. class name to status symbol
  3. exact name, no ancestors
  4. show_exceptions :rescuable in tests
  5. mapped means expected, not reported

basics

~20 s

Map it in rescue_responses when a status and the standard error page are enough everywhere; use rescue_from when the response needs controller work such as a redirect, a flash or a layout. Mappings match the exact class name, while rescue_from matches subclasses.

solid answer

~40 s

`rescue_responses` is a middleware-level table from exception class name to status; `ShowExceptions` uses it for any unhandled exception, so one line such as `config.action_dispatch.rescue_responses["Subscriptions::Expired"] = :payment_required` makes it a 402 app-wide, with `public/402.html` or a generated JSON body. Mapped exceptions also count as expected: they render under the test environment's `show_exceptions = :rescuable` and are not reported as unhandled errors. `rescue_from` runs in the controller, so I use it when an expired subscription should redirect a browser to the pricing page with an alert. Two traps: the mapping looks up the exact class name, so a subclass of a mapped exception still answers 500, and an exception handled by `rescue_from` never reaches the middleware, so nothing logs or reports it unless the handler does.

code

ruby · 11 lines
ruby
# config/application.rb
module MusicApp
  class Application < Rails::Application
    config.load_defaults 8.1

    config.action_dispatch.rescue_responses.merge!(
      "Subscriptions::Expired"      => :payment_required,
      "Subscriptions::TrialExpired" => :payment_required # subclasses are not inherited
    )
  end
end

go deeper

for a junior

Recall that config.action_dispatch.rescue_responses maps an exception class to an HTTP status, and that rescue_from handles an exception inside a controller.

for a middle

Explain the layers: rescue_from runs in the controller and can redirect or render; a mapping picks a status that ShowExceptions turns into the standard page.

for a senior

Catch the exact-class-name trap, use mappings to keep test and reporting behaviour right, and record exceptions yourself when rescue_from swallows them.

for a principal

Define which domain failures are expected outcomes with a fixed status and which need per-surface handling, and keep that list in one reviewed place.

## Two tools at two layers Rails gives you two places to turn an exception into a response, and they live at different layers of the request: - **`rescue_from`** runs **inside the controller**. The handler is controller code: it can redirect with a flash, render a template with the app's layout, read `Current.user` and choose any status. - **`config.action_dispatch.rescue_responses`** runs **in the middleware**. It is a Hash from exception **class name** to a status (`:payment_required`, `:not_found`, or an integer). When an unhandled exception reaches `ActionDispatch::ShowExceptions`, the status is looked up there and the exceptions app renders the page for that status. At boot, the Action Dispatch railtie merges the configured Hash into `ActionDispatch::ExceptionWrapper.rescue_responses`, which already holds Rails' own entries and returns `:internal_server_error` for any name it does not know. ## What a mapping gives you 1. **One line, app-wide.** `config.action_dispatch.rescue_responses["Subscriptions::Expired"] = :payment_required` makes that exception answer 402 wherever it is raised below `ShowExceptions`: in any controller, its filters, its views, or a middleware further in. 2. **The standard pages and formats.** The default exceptions app serves `public/402.html` if you add one, or a generated `{"status":402,"error":"Payment Required"}` body for a JSON request. 3. **Correct behaviour in tests.** The generated `test.rb` sets `show_exceptions = :rescuable`, which renders responses only for mapped exceptions; a mapped exception gives an integration test a 402 to assert, an unmapped one is raised into the test. 4. **Expected-error bookkeeping.** `ShowExceptions` marks mapped exceptions as expected: the request still logs them, but Rails does not report them as unhandled errors the way it reports an unmapped one. ## What rescue_from gives you - Arbitrary responses: a redirect to `/pricing` with an alert is impossible with a mapping, which only picks a status and a page. - Per-controller behaviour: the web controllers can redirect while an API namespace renders JSON. - `is_a?` matching: a handler for a parent class catches its subclasses. - But the exception never reaches the middleware, so it is neither logged as an error by `DebugExceptions` nor reported automatically. If you want it recorded, the handler must do it. ## The exact-name trap The mapping looks up `exception.class.name` **exactly**. It does not walk ancestors. With ```ruby class Subscriptions::Expired < StandardError; end class Subscriptions::TrialExpired < Subscriptions::Expired; end ``` and only `"Subscriptions::Expired"` mapped, a `TrialExpired` answers **500**. Map every concrete class you raise, or handle the family with `rescue_from`, which does use `is_a?`. The same rule explains why mapping `"StandardError"` does nothing for a `NoMethodError`. ## Other details - The value goes through `Rack::Utils.status_code`. An unknown symbol raises `ArgumentError` while the error page is being built, and production falls back to `ShowExceptions`' plain-text failsafe 500. - `:unprocessable_entity` is Rack's obsolete name for 422; on Rack 3.1 and later Rails 8.1's own entries use `:unprocessable_content`. - `ActionView::Template::Error` is unwrapped before the lookup, so a mapped exception raised in a view keeps its status. ## Choosing for the music-streaming app | failure | best tool | why | |---|---|---| | deleted track (`RecordNotFound`) | the existing mapping | 404 page, nothing to add | | expired subscription, browser user | `rescue_from` | must redirect to the pricing page with a message | | expired subscription, mobile API | mapping to `:payment_required` | a status and a generated JSON body are enough | | a bug (`NoMethodError`) | neither | let it become a reported 500 |

  • Subscriptions::TrialExpired inherits from a mapped Subscriptions::Expired, yet production answers 500. Why?
    `ExceptionWrapper` looks the status up with `exception.class.name` as an exact Hash key and falls back to `:internal_server_error`. It does not walk the class's ancestors, so `"Subscriptions::TrialExpired"` needs its own entry, or the family needs a `rescue_from Subscriptions::Expired`, which matches with `is_a?`.
  • Why does mapping an exception change what a Rails integration test sees?
    The generated `test.rb` sets `config.action_dispatch.show_exceptions = :rescuable`, which renders an error response only for classes in `rescue_responses` and raises everything else into the test. Once mapped, the test receives a 402 response it can assert on instead of an exception.

  • Mapping a parent class in rescue_responses also covers its subclasses.
  • rescue_responses can redirect a browser to another page with a flash.
  • An exception handled by rescue_from is still logged and reported by the middleware.
  • :unprocessable_entity is the current status name to use for 422 mappings.
  • rescue_responses only applies to exceptions raised in ApplicationController.