Request Rescue gives Rails applications consistent error responses for malformed queries, unrecognized HTTP methods, missing templates, unsupported formats and invalid Apipie parameters. A controller concern handles exceptions raised in your actions. The Rails engine provides mountable HTML and JSON error pages.
Add gem "request-rescue" to your Gemfile and run bundle install. To try a local checkout, use gem "request-rescue", path: "/path/to/request-rescue".
Include the concern in controllers where you want to handle these exceptions. It also works with ActionController::API.
class ApplicationController < ActionController::Base
include RequestRescue::Controller
end
Mount the pages in the application's routes. The mount name is used by migration redirects.
Rails.application.routes.draw do
mount RequestRescue::Engine, at: "/errors", as: :request_rescue
end
To render unhandled exceptions through Request Rescue, set the exception app in environments that show public error pages. Rails determines their HTTP status. A raised application exception produces a generic 500 response.
# config/environments/production.rb
config.exceptions_app = RequestRescue::ExceptionsApp
| Request or exception | Default in production | With legacy_responses = true |
|---|---|---|
| Conflicting nested query parameter types | 400 | 400 |
| HTTP method unrecognized by Rails | 405 JSON | 405 JSON with {"errors":["Method not allowed"]} |
| Unsupported controller format, including a template that exists only in other formats | 404 | 302 to the mounted not_found page |
| Template missing in every format | Raised, so Rails returns 500 | 302 to the mounted not_found page |
| Invalid cross-origin JavaScript request | 403 | Empty 200 |
| Missing or invalid Apipie parameter | 422 | 302 to the mounted invalid_params page |
Mounted /not_found, /invalid_params, /404, /500 |
404, 422, 404, 500 respectively | 200 with the corresponding error page |
HTML applications render error pages by default. Clients can request JSON with a .json path, a format parameter, a route's format default or Accept: application/json. API-only applications default to JSON. HEAD requests return the status and headers with an empty body. Apipie integration is available when the host loads apipie-rails.
The middleware is installed automatically after ActionDispatch::RemoteIp, where feedmob-rescue checked requests. Malformed queries and unrecognized methods are rejected before the Rails request log and any middleware the application adds.
Development re-raises handled controller exceptions for debugging. Cross-origin script exceptions also propagate in the test environment.
- Replace the old Gemfile entry and change
include Feedmob::Rescuetoinclude RequestRescue::Controller. - Replace the old engine with
RequestRescue::Engineat the same mount path. Existing root mounts can continue usingat: "/". Migration redirects use the mount name, which Rails sets torequest_rescueunless you pass a differentas:. Keep the application's Apipie dependency if its controllers use Apipie. - Set
config.request_rescue.legacy_responses = truein the application configuration to preserve the previous redirects and empty 200 response to cross-origin script requests in production. - Replace
config.exceptions_app = self.routeswithconfig.exceptions_app = RequestRescue::ExceptionsApp. Migration mode does not depend on the exception app, so the redirects from step 3 stay the same.
With self.routes, a routing miss or an application exception renders the 404 or 500 page with status 200, so load balancers and monitoring do not count it as an error. Only /404 and /500 are routed, so other statuses, such as the 400 from params.require, return an empty body. RequestRescue::ExceptionsApp renders an error page with the status Rails assigns. Keep self.routes only while something depends on status 200, and keep the engine mounted at / in that case.
Check these differences when testing a migration.
- The old error pages redirected requests that accept JSON to
/not_found, including requests for/not_founditself, so a client following redirects never got a response. Withexceptions_app = self.routes, routing misses,.jsonpaths and application exceptions did the same. In migration mode the new pages answer these requests with status 200 and a JSON body such as{"errors":["Page not found"]}. Controller redirects for unsupported formats and Apipie errors still apply to JSON requests. - The old engine rendered ERB views through the host's
ApplicationController. The new engine serves standalone Rack responses. Check any error-page branding, layout overrides or controller callbacks your application relies on. - Migration mode validates the encoding of query values before routing. In version 0.1.3, a mounted page that ignores its query can return 200 for invalid UTF-8. See the changelog for the correction. With migration mode off, Rails can apply per-action parameter encodings.
- The new middleware returns 400 for conflicting nested parameter types. On the Rails 6.1 migration baseline the old middleware let the Rack parsing exception propagate. The new method check also requires the verb casing Rails recognizes.
Before switching a production application, exercise its error routes, an Apipie endpoint if applicable, and any clients that follow redirects. Once clients can consume direct 404, 403 and 422 responses, disable migration mode. Without migration mode, a template that is missing in every format raises and reaches your error reporting as a 500. To roll back, restore the old gem and lockfile, concern, engine and exception app together.
Run the verifier under the Ruby version for the selected Rails and Rack pair.
RBENV_VERSION=3.0.3 APIPIE_VERSION=0.8.1 rbenv exec ruby bin/verify 6.1.5 2.2.4
The verifier builds and installs the gem into a temporary directory, boots a Rails host and exercises its full Rack stack. It writes a package, dependency lockfile and JSON request results with the package SHA-256 under pkg/. Omit APIPIE_VERSION to verify installation without the optional adapter. Set VERIFY_PACKAGE to an existing build to test the same bytes across runtimes. Set VERIFY_LOCK to a previous result’s lockfile to replay its dependency resolution. See the compatibility matrix for the seven targeted Ruby/Rails pairs and their Rack versions.
Open Actions → Publish gem to RubyGems → Run workflow. Choose patch, minor or major under Version increment. The workflow calculates the target from the version in the selected branch. Leave Publish to RubyGems unchecked to build and test the package. To publish it, select main and check the box.
After publishing, the workflow tags the source and opens a version update PR with the repository's built-in GITHUB_TOKEN. A maintainer with write access selects Approve workflows to run on the PR. Wait for All request tests passed, then merge the version update before the next release.
For a version-only update, CI verifies the tag, the version change and the published RubyGems version. Other changes and release candidates run the full compatibility matrix. If recording the release fails after upload, rerun the failed jobs in the original run.
Each published tag has a GitHub Release with release notes, the verified gem and its SHA-256, and source code archives in ZIP and tar.gz formats. To include a short user-facing summary, add a ## X.Y.Z section to CHANGELOG.md before starting the release. GitHub also generates notes from merged pull requests.
MIT.