skip to content

Rescue Handlers & Error Pages

rescue_from turns exceptions into responses, rescue_responses maps the rest to statuses and static pages, and show_exceptions decides who sees what. Interviewers ask why a missing record gives a 404.

part ofRuby on Railsread it →
on this pageshow

explore

questions

5

In a Rails 8.1 app in production, why does Track.find with an id that does not exist show a 404 page instead of a 500?

level: juniorimportance: must knowfreq 62%

answer

  1. find raises RecordNotFound
  2. a class-name to status table
  3. Active Record's railtie adds :not_found
  4. ShowExceptions calls the exceptions app
  5. public/404.html served by PublicExceptions

basics

~10 s

Track.find raises ActiveRecord::RecordNotFound, which Active Record maps to :not_found in config.action_dispatch.rescue_responses. In production the ShowExceptions middleware turns the unhandled exception into a 404 and serves public/404.html.

solid answer

~40 s

`find` raises `ActiveRecord::RecordNotFound` when no row matches. If no `rescue_from` handles it, it leaves the controller. `DebugExceptions` would show the debug page only when `consider_all_requests_local` is true, which production turns off, so it reaches `ShowExceptions`. That middleware looks the exception's class name up in `rescue_responses`; Active Record's railtie registers `RecordNotFound => :not_found` there. It rewrites the request to `GET /404` and calls the exceptions app, by default `ActionDispatch::PublicExceptions`, which serves `public/404.html` (or a JSON body for a JSON request). Any class not in that table falls back to `:internal_server_error` and `public/500.html`. In development the same exception shows the debug page, still with status 404.

code

ruby · 7 lines
ruby
class TracksController < ApplicationController
  def show
    # No row with this id -> ActiveRecord::RecordNotFound
    # -> rescue_responses says :not_found -> public/404.html
    @track = Track.find(params[:id])
  end
end

go deeper

for a junior

Recall that find raises ActiveRecord::RecordNotFound and that production answers it with public/404.html and status 404, while development shows the debug page.

for a middle

Explain the chain: no rescue_from, DebugExceptions skipped in production, ShowExceptions maps the class through rescue_responses and calls PublicExceptions.

for a senior

Mention what bends the default: unmapped classes become 500, Template::Error is unwrapped, JSON requests get a generated body, and localized public pages exist.

for a principal

Treat the status table as the contract for expected failures, and decide which domain errors join it and which need controller handling.

## The short answer `Track.find(999)` raises **`ActiveRecord::RecordNotFound`**. Nothing in the controller rescues it, so it travels up through the middleware stack. There, Rails looks the exception's class name up in a table of known exceptions, finds `:not_found`, and serves the static page **`public/404.html`** with status 404. An exception the table does not know becomes a 500 and `public/500.html`. ## The path of the exception, step by step 1. **The action raises.** In a music-streaming app, `TracksController#show` calls `Track.find(params[:id])` and the id does not exist. 2. **`rescue_from` gets the first chance.** If the controller (or `ApplicationController`) declared `rescue_from ActiveRecord::RecordNotFound`, that handler runs and the story ends inside the controller. By default nothing is declared. 3. **`ActionDispatch::DebugExceptions`** sees it next. It renders the detailed debug page only when detailed exceptions are on, which `config.consider_all_requests_local` controls; the generated `production.rb` sets it to `false`, so in production it logs the error and re-raises. 4. **`ActionDispatch::ShowExceptions`** catches it. With `config.action_dispatch.show_exceptions` at its default `:all`, it wraps the exception, computes the status from **`rescue_responses`**, rewrites the request to `GET /404` and calls the **exceptions app**. 5. **The exceptions app**, by default `ActionDispatch::PublicExceptions.new(Rails.public_path)`, reads `public/404.html` and returns it with status 404. ## Where the 404 comes from `ActionDispatch::ExceptionWrapper.rescue_responses` is a Hash from exception **class name** to status, with a default of `:internal_server_error`. Action Dispatch fills in its own entries, and **Active Record's railtie merges its own** through `config.action_dispatch.rescue_responses`: | exception | status | |---|---| | `ActiveRecord::RecordNotFound` | `:not_found` (404) | | `ActiveRecord::StaleObjectError` | `:conflict` (409) | | `ActiveRecord::RecordInvalid`, `ActiveRecord::RecordNotSaved` | `:unprocessable_content` (422) | | `ActionController::RoutingError`, `AbstractController::ActionNotFound` | `:not_found` (404) | | `ActionController::UnknownFormat` | `:not_acceptable` (406) | | anything else | `:internal_server_error` (500) | So the 404 is not a special case in the controller: it is one row in a table that any exception class can join. ## What the visitor actually receives - **An HTML request** gets the file. `PublicExceptions` first tries `public/404.<locale>.html` for the current `I18n.locale`, then `public/404.html`. - **A JSON or XML request** gets a small generated body such as `{"status":404,"error":"Not Found"}` in that format instead of the file. - **A HEAD request** gets the status and headers with an empty body. - If no file exists for the status, the response is that status with an empty body. A new Rails 8.1 app ships `400.html`, `404.html`, `406-unsupported-browser.html`, `422.html` and `500.html` in `public/`. They are plain, self-contained HTML: no ERB, no layout, no asset pipeline, because they must render even when the app cannot. ## Development looks different The generated `development.rb` sets `consider_all_requests_local = true`, so step 3 renders the debug page with the backtrace, still with status 404. That is why developers often believe Rails "doesn't do 404s" until they first deploy. ## Checking it yourself 1. Run the app in production mode, or temporarily set `config.consider_all_requests_local = false` in development. 2. Request `/tracks/999` in a browser: the page is `public/404.html` and the status, visible in the browser's network panel, is 404. 3. Repeat with `Accept: application/json` and the body becomes a two-key JSON object. 4. Raise a `NoMethodError` in the action and the same path produces `public/500.html` with status 500, because that class is not in the table. ## Details worth knowing - **Errors raised inside a view are unwrapped.** A `RecordNotFound` raised while a template renders arrives wrapped in `ActionView::Template::Error`; the wrapper class is on a list Rails unwraps, so the status still comes from `RecordNotFound` and the visitor still gets a 404. - **`find_by` returns `nil` instead of raising**, so code that goes on to call a method on the result fails with `NoMethodError`, which is unmapped and becomes a 500. - **Mapped exceptions are treated as expected outcomes.** Rails still logs them, but does not report them as unhandled errors the way it reports an unmapped one.

  • Why does the same missing Track show a stack trace page in development?
    The generated `development.rb` sets `config.consider_all_requests_local = true`, so `ActionDispatch::DebugExceptions` renders its detailed page before `ShowExceptions` gets a chance. The status is still 404, taken from the same `rescue_responses` entry; only the body differs.
  • Can you show a translated 404 page without writing any controller code?
    Yes. `ActionDispatch::PublicExceptions` first looks for `public/404.<locale>.html` using the current `I18n.locale`, and only then falls back to `public/404.html`. Adding `public/404.de.html` gives German visitors a German page, as long as the locale is set for the request.

  • Rails returns 404 because the controller checks whether the record was found.
  • public/404.html is rendered through the application layout with ERB.
  • Any exception raised in a show action becomes a 404.
  • Production shows the debug page unless you write a rescue_from.
  • A RecordNotFound raised inside a view turns into a 500 because it is wrapped.
open as a page

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%

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.

open as a page

In Rails 8.1, how do config.action_dispatch.show_exceptions and config.consider_all_requests_local together decide what a request that raises receives?

level: middleimportance: should knowfreq 38%

basics

~10 s

show_exceptions decides whether Rails renders a response for an exception (:all, :rescuable for mapped classes only, :none); consider_all_requests_local decides whether that response is the detailed debug page or the public error page.

open as a page

How do you serve dynamic error pages with the app's layout in Rails 8.1 through config.exceptions_app, and what must that error app avoid?

level: seniorimportance: should knowfreq 28%

basics

~20 s

Set config.exceptions_app to the app's routes (or any Rack app); ShowExceptions then sends GET /404, /500 and so on to an errors controller. It must set the status explicitly, cover every status, and never raise, or Rails falls back to a plain-text 500.

open as a page

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%

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.

open as a page