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?
answer
- default is PublicExceptions on public/
- config.exceptions_app = self.routes
- request rewritten to GET /404
- env action_dispatch.exception
- failsafe plain-text 500
basics
~20 sSet 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.
solid answer
~40 sBy default `ShowExceptions` calls `ActionDispatch::PublicExceptions`, which serves static `public/<status>.html`. I set `config.exceptions_app = self.routes` and add `match "/404", to: "errors#not_found", via: :all` and friends: `ShowExceptions` rewrites the failed request to `GET /404`, keeps the original path in `env["action_dispatch.original_path"]` and the exception in `env["action_dispatch.exception"]`. The errors controller renders with the layout, but it must pass `status:` itself, route every status the app can produce (an unrouted one answers with an empty body), skip authentication filters and handle JSON. Above all it must not raise: if it does, Rails returns its plain-text failsafe 500. So I keep the 500 page free of database calls, or keep `public/500.html` for it via a lambda.
code
ruby · 11 linesclass ErrorsController < ActionController::Base
layout "application"
def not_found
@path = request.env["action_dispatch.original_path"]
respond_to do |format|
format.html { render status: :not_found }
format.json { render json: { error: "not_found" }, status: :not_found }
end
end
endgo deeper
Recall that production error pages are static files in public/, and that config.exceptions_app lets a Rails app render its own instead.
Explain the hand-off: ShowExceptions rewrites the request to GET /<status> and passes the exception and original path in the env.
Build it safely: explicit statuses, every status routed, no authentication or database work on the 500 path, JSON handled, and the failsafe understood.
Weigh branded error pages against the risk that the error path fails with the app, and decide which statuses may be dynamic.
## Why replace the static pages The default exceptions app, `ActionDispatch::PublicExceptions`, serves the static files in `public/`. They cannot use ERB, layouts or helpers, which is deliberate: a 500 page must render even when the app cannot. For a music-streaming app, though, a 404 that keeps the site's navigation and suggests popular playlists is worth having. **`config.exceptions_app`** is the hook: any Rack application that `ShowExceptions` calls instead of `PublicExceptions`. ## What ShowExceptions hands the exceptions app When it decides to render, `ShowExceptions`: 1. computes the status from `rescue_responses` (404 for a missing record), 2. stores the original path in `env["action_dispatch.original_path"]` and the original method in `env["action_dispatch.original_request_method"]`, 3. puts the exception (unwrapped from `ActionView::Template::Error` if needed) in `env["action_dispatch.exception"]`, 4. **rewrites the request** to `GET /404` (path_info = `/#{status}`, method = GET) and calls the app. Whatever response the app returns is what the visitor gets, status included; the one exception is a response marked `X-Cascade: pass`, which `ShowExceptions` replaces with the original status and an empty body. ## Option A: route errors through the app's own router ```ruby # config/application.rb config.exceptions_app = self.routes # config/routes.rb match "/404", to: "errors#not_found", via: :all match "/500", to: "errors#internal_error", via: :all ``` `ErrorsController` actions render normal templates with the layout. Three rules apply: - **Set the status explicitly** (`render status: :not_found`). A plain render would answer 200 and tell search engines the page exists. - **Route every status you can produce** (400, 404, 406, 422, 500 at least). For an unrouted status the router passes, and `ShowExceptions` returns that status with an **empty body**. - **Skip filters that can fail or redirect**, such as authentication, so the error page renders for signed-out visitors. ## Option B: a lambda that picks per status A Rack app can be a lambda, which allows a dynamic 404 and a static 500: ```ruby config.exceptions_app = ->(env) do if env["PATH_INFO"] == "/404" ErrorsController.action(:not_found).call(env) else ActionDispatch::PublicExceptions.new(Rails.public_path).call(env) end end ``` ## What the exceptions app must never do: fail If the exceptions app itself raises, `ShowExceptions` gives up and returns its **failsafe**: a plain-text 500 starting "500 Internal Server Error" that tells administrators to read the logs, with nothing from your design. That is why: - The 500 page should not query the database, call external services or depend on the signed-in user: the error being reported may be exactly that the database is down. - Layout code that touches models (a "recently played" sidebar) belongs on the 404 page at most. - Keeping `public/500.html` as the 500 response, as in option B, is the safest design. ## Testing it In development `consider_all_requests_local` is `true`, so `DebugExceptions` renders the debug page and the exceptions app never runs. To see the real pages locally, set it to `false` temporarily, or write an integration test in which the app runs with `consider_all_requests_local = false` and `show_exceptions = :all`. ## A checklist before shipping 1. Every status the app can raise has a route or a fallback. 2. Every action sets its status explicitly. 3. The errors controller does not inherit authentication or other filters that can redirect or fail. 4. The 500 path touches no database, cache or external service. 5. An integration test runs with `consider_all_requests_local = false` and asserts the status and a piece of the body. ## Formats `PublicExceptions` renders JSON or XML bodies for API requests. A custom errors controller has to do the same with `respond_to`, or an API client asking for JSON receives an HTML page.
- Your exceptions app routes only /404 and /500. What does a visitor get for an InvalidAuthenticityToken (422)?`ShowExceptions` sends `GET /422` to the router, no route matches, and the router answers with `X-Cascade: pass`. `ShowExceptions` then returns status 422 with an empty body. Route every status the app produces, or delegate unknown ones to `ActionDispatch::PublicExceptions`.
- Why might the custom 500 page render fine in staging but show a bare text message during a real outage?If the outage is the database and the 500 page's layout queries it, rendering the error page raises too. `ShowExceptions` rescues that and returns its failsafe plain-text 500. Error pages for 5xx statuses should depend on nothing that can be the cause of the error.
- The errors controller can rely on Rails to keep the original 404 status.
- If the error page raises, Rails falls back to public/500.html.
- The exceptions app receives the original request path and HTTP method unchanged.
- config.exceptions_app pages also replace the debug page in development.
- Routing only /404 is enough; other statuses fall back to the static files.