Skip to main content
Published in Engineering Insights

Rails Exception Handling: Wrapping Up Exceptional Behavior

Rails Exception Handling: Wrapping Up Exceptional Behavior
Table of contents
  1. Exceptional Behavior in Rails
  2. Reset
  3. Revisit The Wrapper
  4. Regifting (Rails 6 Redux)
  5. Thank You Card
  6. Rails exception handling, layer by layer
    1. The rescue block: begin, rescue, ensure and retry
    2. Exception handling in a controller with rescue_from
    3. Mapping exceptions to status codes
    4. Error reporting and background jobs

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#

  1. (W)rapping About Exceptional Behavior In Rails
  2. 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:

Ruby
def initialize(backtrace_cleaner, exception)
  @backtrace_cleaner = backtrace_cleaner
  @exception = original_exception(exception)end

The exception that is passed in is modified. Let's look at this original_exception method.

Ruby
def original_exception(exception)
  if @@rescue_responses.has_key?(exception.cause.class.name)
    exception.cause
  else
    exception
  end
end

Recall 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.

Ruby
def initialize(backtrace_cleaner, exception)
  @backtrace_cleaner = backtrace_cleaner
  @exception = exception
end

No 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.

Ruby
def unwrapped_exception
  if wrapper_exceptions.include?(exception.class.to_s)
    exception.cause
  else
    exception
  end
end

Rather 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.

LayerWhere it livesWhat it does
begin and rescueInside a method or blockRescues StandardError and its subclasses by default; ensure always runs
rescue_fromA controller and its subclassesSends an exception type to a handler method, Proc or block
rescue_responsesApplication configMaps exception class names to HTTP status codes
show_exceptions and exceptions_appApplication configDecide 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.

Ruby
attempts = 0
begin
  charge_card(order)
rescue Timeout::Error => error
  warn error.message
  attempts += 1
  retry if attempts < 3
ensure
  log_attempt(order)
end

Exception 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:

Ruby
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
end

This 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.

Ruby
# config/application.rb
config.action_dispatch.rescue_responses["MyAuthenticationError"] = :unauthorized

In 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. 

Frequently asked questions

Why did Rails 5 return 404 for a RuntimeError?

The RuntimeError was raised while handling ActiveRecord::RecordNotFound. The original_exception method selected that cause because it was in @@rescue_responses. RecordNotFound maps to 404.

What changed in the Rails 6 wrapper?

The initializer keeps the passed exception instead of calling original_exception. Status lookup uses unwrapped_exception, which checks wrapper_exceptions to decide whether to use the cause.

Which exception gets unwrapped in the Rails 6 example?

ActionView::Template::Error uses the status of its cause. Other exceptions use their own status.

Why does RuntimeError produce 500 in Rails 6?

RuntimeError is not in wrapper_exceptions, so its ActiveRecord::RecordNotFound cause is not used for status lookup. RuntimeError has no special handling in rescue_responses, so the result is 500.

How do I return a 404 for a custom exception in Rails?

Add the exception class name to the rescue_responses setting under config.action_dispatch, with the not_found status. Use []= so the default pairs stay. You can also rescue it in a controller with rescue_from and render a response with status 404 yourself.

What is the difference between rescue and rescue_from in Rails?

rescue is Ruby syntax that catches an exception inside one method or begin block. rescue_from is a Rails controller method that sends an exception type to a handler for every action in that controller and its subclasses, so the handling lives in one place.

Where to go from here

  • Your US company does over $10M a year in revenue, and its order system is holding you back.

    Talk to Pete Whiting
  • You want AI to save your company money. With Compass, if we don't find at least $350,000 a year in savings, you don't pay.

    See how Compass works
  • Comparing firms? Here are the questions to ask any of them.

    See the questions
  • Pricing a build? Here is what it costs and how the price holds.

    See the price guide
  • Everyone else: get our newest posts by email.

    Get the newsletter

Stay In The Loop

Never miss an update. Get the latest blogs, webinars, and expert insights straight to your inbox from The Gnar.