This post is for Rails developers chasing a status code that changed after an upgrade. It finishes a two-part look at Rails exception handling: why the same error returned a 404 in Rails 5 and a 500 in Rails 6. It ends with a short guide to the layers of error handling in a Rails app, from a Ruby rescue block to rescue_from, rescue_responses and error pages.
Exceptional Behavior in Rails#
- (W)rapping About Exceptional Behavior In Rails
- Wrapping Up Rails Exceptional Behavior
Reset#
In our last post, we encountered some inconsistent behavior between Rails 5 and Rails 6. In Rails 5, raising a RuntimeError in a controller after rescuing from an ActiveRecord::RecordNotFound exception was still returning a 404 HTTP status code. In Rails 6, the status code is a 500.
We looked around, and we think we've isolated the area of interest to be in the ExceptionWrapper class.
Revisit The Wrapper#
We looked into what was creating our wrapper and discovered that we were always passing it the RuntimeError. After taking a much-needed break, we start reading the code again, and, almost immediately, we see a transformation:
def initialize(backtrace_cleaner, exception)
@backtrace_cleaner = backtrace_cleaner
@exception = original_exception(exception)endThe exception that is passed in is modified. Let's look at this original_exception method.
def original_exception(exception)
if @@rescue_responses.has_key?(exception.cause.class.name)
exception.cause
else
exception
end
endRecall that our RuntimeError is raised as a result of handling an ActiveRecord::RecordNotFound exception. The RecordNotFound exception is the cause of the RuntimeError. We previously discovered that RecordNotFound is added to @@rescue_responses in ActiveRecord's railtie.
The cause of our exception is in the hash, and as such, the cause is set as the @exception variable in the initializer. That cause is RecordNotFound, and a RecordNotFound exception is supposed to return a 404 status code.
We can now explain why a 404 is returned!
Regifting (Rails 6 Redux)#
We now have a handle on the behavior in Rails 5; however, this investigation started because we noticed it was different in Rails 5 and Rails 6. Let's check in on the ExceptionWrapper initializer in Rails 6.
def initialize(backtrace_cleaner, exception)
@backtrace_cleaner = backtrace_cleaner
@exception = exception
endNo longer are we retrieving the original_exception. That doesn't tell the whole story though. When we ask for the status code, we're not using @exception. Instead, we now have an unwrapped_exception to investigate.
def unwrapped_exception
if wrapper_exceptions.include?(exception.class.to_s)
exception.cause
else
exception
end
endRather than looking in rescue_responses, we're now looking in wrapper_exceptions, which it appears is a list of one exception that should behave particularly exceptionally.
If the exception is an ActionView::Template::Error, then look up the status code based on the cause of the exception. Otherwise, determine it based on the exception itself.
RuntimeError isn't in this list of wrapper_exceptions, so we don't use the cause (ActiveRecord::RecordNotFound) to determine the status code. We use the RuntimeError itself. That has no special handling in rescue_responses, so a 500 HTTP status code is returned.
Thank You Card#
The commit that makes this change contains a very well-worded description of this scenario, including:
When the cause is mapped to an HTTP status code the last exception is unexpectedly uwrapped
Thanks to Yuki Nishijima for fixing this!
Rails exception handling, layer by layer#
Rails exception handling works in layers. Ruby's begin and rescue handle an error inside one method. A controller's rescue_from handles an exception type across every action in that controller. Anything still unhandled reaches the ExceptionWrapper this post walked through, which looks up the HTTP status that Rails then uses to render an error page. Knowing which layer catches an error tells you which status code and error message the user sees.
| Layer | Where it lives | What it does |
|---|---|---|
| begin and rescue | Inside a method or block | Rescues StandardError and its subclasses by default; ensure always runs |
| rescue_from | A controller and its subclasses | Sends an exception type to a handler method, Proc or block |
| rescue_responses | Application config | Maps exception class names to HTTP status codes |
| show_exceptions and exceptions_app | Application config | Decide whether Rails renders an error page, and which app renders it |
The rescue block: begin, rescue, ensure and retry#
The Ruby documentation on exceptions sets the basic rules. A rescue clause with no class catches StandardError and its subclasses. Rescue clauses are matched from the top and only one runs. retry starts the begin block again, so guard it to avoid an infinite loop. ensure always runs, whether or not an exception was raised, and else runs only when nothing was raised.
Exceptions are objects. Every one is an instance of Exception or a subclass, StandardError is a subclass of Exception, and Kernel#raise raises one, usually with an error message. Rescue the specific classes you expect, such as ActiveRecord::RecordNotFound. Rescuing Exception itself also catches errors Ruby uses to stop a program, such as Interrupt and SystemExit, and can hide the real cause of a failure. For errors your own code raises, define a custom exception class that inherits from StandardError.
attempts = 0
begin
charge_card(order)
rescue Timeout::Error => error
warn error.message
attempts += 1
retry if attempts < 3
ensure
log_attempt(order)
endException handling in a controller with rescue_from#
The Action Controller guide describes rescue_from as a way to handle exceptions of a certain type, or several types, in an entire controller and its subclasses. The exception object is passed to the handler, which can be a method, a Proc or a block. The guide's example catches ActiveRecord::RecordNotFound:
class ApplicationController < ActionController::Base
rescue_from ActiveRecord::RecordNotFound, with: :record_not_found
private
def record_not_found
render plain: "Record Not Found", status: 404
end
endThis is where the behavior in this series shows up. If a handler raises a new exception instead of rendering, Ruby sets the original exception as the new one's cause. As the code above showed, Rails 6 picks the status from the new exception unless it is an ActionView::Template::Error. Render the response you want inside the handler, and the status stays the one you chose.
Put shared handlers in ApplicationController, so every controller returns the same response for the same error, whether it renders HTML or JSON.
Mapping exceptions to status codes#
The Rails configuration guide documents config.action_dispatch.rescue_responses, a hash of exception class names and HTTP statuses. The defaults map ActiveRecord::RecordNotFound to not_found, ActionController::ParameterMissing to bad_request, ActiveRecord::RecordInvalid to unprocessable_entity and ActiveRecord::StaleObjectError to conflict. Add your own pairs with []= or merge! so the defaults stay in place, and read ActionDispatch::ExceptionWrapper.rescue_responses to see the full map.
# config/application.rb
config.action_dispatch.rescue_responses["MyAuthenticationError"] = :unauthorizedIn production, Rails then renders the matching static page from the public folder, such as 404.html or 500.html. config.exceptions_app sets which app renders those pages, and config.action_dispatch.show_exceptions controls whether Rails renders an error page at all or lets the exception raise.
Error reporting and background jobs#
Rails 7 and later also have an error reporter, Rails.error. The error reporting guide explains that it gives error tracking libraries one place to capture unhandled errors, without their own Rack middleware. A subscriber is any Ruby object with a report method, registered with Rails.error.subscribe. Background jobs fail outside the request cycle, so Active Job handles them with retry_on, which retries a job for the exceptions you list, and discard_on, which drops a job for them.
Learn more about how The Gnar builds Ruby on Rails applications.


