skip to content

In a Rails controller, how do rescue_from handlers declared with with: or a block work, and which runs when several match?

level: middleimportance: must knowfreq 55%

answer

  1. ActiveSupport::Rescuable under the hood
  2. with: :method_name or a block
  3. wraps callbacks, action and render
  4. last declared is checked first
  5. falls back to exception.cause

basics

~20 s

rescue_from registers a method (with:) or a block for exception classes raised in a controller's callbacks, action or rendering. Rails checks handlers from the last declared upward, subclass before parent, and runs the first whose class matches.

solid answer

~40 s

`rescue_from Subscriptions::Expired, with: :send_to_pricing` or `rescue_from ActiveRecord::RecordNotFound do |e| ... end` registers a handler; it receives the exception if it takes an argument and runs on the controller, so it can redirect or render. It wraps `process_action`, so it covers before, around and after callbacks, the action and rendering, but not routing errors or middleware. Handlers are searched in reverse declaration order, with a subclass's handlers ahead of inherited ones, and the first `is_a?` match wins; there is no ranking by specificity, so a `rescue_from StandardError` declared after a specific handler swallows it. If nothing matches, Rails tries `exception.cause`. A handler that raises sends the new exception to the middleware, not to another handler.

code

ruby · 12 lines
ruby
class ApplicationController < ActionController::Base
  rescue_from "Subscriptions::Expired", with: :send_to_pricing
  rescue_from ActiveRecord::RecordNotFound do |error|
    logger.info "missing: #{error.model} #{error.id}"
    render "errors/track_missing", status: :not_found
  end

  private
    def send_to_pricing(error)
      redirect_to pricing_path, alert: "Your plan ended on #{error.ended_on.to_fs(:long)}."
    end
end

go deeper

for a junior

Recall the two forms, with: :method and a block, and that the handler receives the exception and must render, redirect or head.

for a middle

Explain the lookup: reverse declaration order, subclass first, is_a? matching, the cause fallback, and that callbacks and rendering are covered but routing errors are not.

for a senior

Spot the StandardError-declared-last bug, keep handlers from raising, and decide which errors deserve a controller response versus the default status mapping.

for a principal

Set the team rule for where rescue_from lives (ApplicationController, concerns, per controller) so handlers stay few, ordered and visible to error reporting.

## What rescue_from does `rescue_from` comes from `ActiveSupport::Rescuable`, which `ActionController::Rescue` mixes into every controller. It registers a **handler** for one or more exception classes: - `rescue_from Subscriptions::Expired, with: :send_to_pricing` names a **method**. - `rescue_from ActiveRecord::RecordNotFound do |error| ... end` passes a **block**. - With neither, Rails raises `ArgumentError` ("Need a handler..."). A handler that takes one argument receives the exception object; one that takes none is called without it. Methods and blocks run on the controller instance, so they can call `render`, `redirect_to`, `head`, use `flash` and read `Current` attributes. Class names may be given as **strings** (`"Subscriptions::Expired"`), resolved only when an exception is matched, which avoids loading the class at boot. ## What it covers `ActionController::Rescue` wraps `process_action`, and its place in the controller's module list puts it **outside the callbacks**. So `rescue_from` sees exceptions raised in: 1. `before_action`, `around_action` and `after_action` callbacks, 2. the action itself, 3. rendering, including an implicit render after the action returns. It does **not** see exceptions raised before a controller exists, most notably `ActionController::RoutingError` for a URL no route matches, nor anything raised in middleware. ## Which handler runs Handlers are stored in a class attribute, `rescue_handlers`, in declaration order. A subclass's handlers are appended after the inherited ones. When an exception arrives, Rails walks that list **in reverse** and runs the **first** handler whose class matches with `is_a?`. In practice: | rule | consequence | |---|---| | later declarations win | the bottom `rescue_from` in a class is checked first | | subclasses win over parents | a handler in `TracksController` beats one in `ApplicationController` | | matching is `is_a?` | a handler for `Subscriptions::Error` also catches its subclasses | | no ranking by specificity | Rails does not prefer the most specific class; order decides | If nothing matches the exception, Rails tries the same lookup on `exception.cause`, so a handler can catch an error that arrived wrapped in another. ## The classic ordering bug ```ruby class ApplicationController < ActionController::Base rescue_from ActiveRecord::RecordNotFound, with: :track_missing rescue_from StandardError, with: :something_broke # checked first end ``` `StandardError` is declared last, so it is checked first, and every `RecordNotFound` lands in `something_broke`. Declaring the broad handler first would let the specific one win. The Rails guide goes further and warns against rescuing `StandardError` or `Exception` at all: it also swallows the bugs you need to see, bypasses the 404 mapping that `rescue_responses` gives `RecordNotFound`, and keeps those errors from being reported as unhandled. ## Instrumentation and testing - Each time a handler is chosen, Action Controller publishes a `rescue_from_callback.action_controller` notification carrying the exception, so a log subscriber can count how often each handler fires. - An integration test is the honest test of a handler: request the URL, then assert the redirect or status. A unit test that calls the handler method directly skips the lookup order, which is where the bugs live. ## When the handler itself fails A handler that raises does not hand the new exception to another `rescue_from` handler. It leaves the controller and is treated by the middleware like any unhandled exception, typically ending as a 500. Keep handlers small and free of anything that can fail for the same reason as the original error. ## A worked example from a music-streaming app - `Subscriptions::Expired` raised by a `before_action` that guards premium tracks: redirect to the pricing page with an alert. Only a controller handler can do that. - `ActiveRecord::RecordNotFound` for a deleted track: render a friendly page with the app's layout and status 404. - Everything else: let it propagate, so Rails shows `public/500.html` and records it as a real error. Each handler must produce a response, whether `render`, `redirect_to` or `head`; one that only logs leaves the client an empty response.

  • Why can a rescue_from ActionController::RoutingError in ApplicationController never fire for an unknown URL?
    `rescue_from` wraps `process_action`, which runs only once a route has picked a controller and action. For a URL no route matches, the router passes, `ActionDispatch::DebugExceptions` raises `RoutingError` in the middleware, and no controller instance exists to rescue it. Rails maps it to 404 through `rescue_responses`; a custom page needs `config.exceptions_app` or a catch-all route.
  • A TracksController declares its own rescue_from for RecordNotFound and ApplicationController declares one too. Which runs?
    The TracksController one. A subclass's handlers are appended after the inherited ones and the list is searched in reverse, so the subclass's declarations are checked first, even for the same exception class.
  • Does a rescue_from handler for Subscriptions::Error catch Subscriptions::Expired < Subscriptions::Error?
    Yes. Matching uses `is_a?`, so a handler for a parent class catches its subclasses unless a later-declared handler for the subclass matches first. That differs from `rescue_responses`, which looks up the exact class name.

A stack of standing orders on a desk where the newest sheet sits on top: the clerk reads from the top down and follows the first sheet that fits the case, so a broad "handle anything" sheet laid on last hides every specific one beneath it.

  • Rails picks the most specific matching rescue_from regardless of declaration order.
  • rescue_from only covers the action body, not before_action callbacks.
  • A rescue_from in ApplicationController can catch RoutingError for unmatched URLs.
  • If a handler raises, Rails passes the new error to the next matching handler.
  • rescue_from StandardError is a harmless safety net that keeps 404s intact.