ActionController: rescue_from
This course follows the one rescue_from line in this app's ApplicationController, which catches ActiveRecord::RecordNotFound and renders a custom not-found page. It covers the with: and block forms, how handler arity decides whether the exception is passed, and why declaration order outranks specificity when several handlers match. It also looks at the ActiveRecord exception family under is_a?, Rails' default mapping of RecordNotFound to a 404, and what happens when no handler matches or a handler fails. The last lesson is a small simulator of the search algorithm.
What you'll learn
- ✓How one rescue_from line on ApplicationController turns a bad slug into a custom not-found page
- ✓The with: and block forms, and how handler arity decides whether the exception is passed in
- ✓Why the most recently declared handler wins, and how handlers are inherited
- ✓How is_a? matching covers a whole exception family, and when to name one exact class
- ✓How Rails maps RecordNotFound to a 404 and what a custom rescue_from adds
- ✓What happens when no handler matches or the handler itself raises
rescue_from: this app's one line, from a bad slug to a custom page
Course and lesson pages in this app are found by slug, not by numeric id. The query objects behind them:
Read the full lesson free →Curriculum
7 lessonsrescue_from: this app's one line, from a bad slug to a custom page
Traces a missing course or lesson slug from find_by! through rescue_from to the render_not_found page.
with: or a block: the two forms rescue_from accepts
Compares the with: and block forms, which share one slot, and shows how arity controls the exception argument.
Multiple rescue_from calls: declaration order beats specificity
Shows that handlers are searched newest first, so declaration order beats specificity, and that subclasses inherit them.
is_a? and the ActiveRecord exception family this app never had to name
Explains how rescuing ActiveRecordError would catch four sibling exceptions, and why this app names RecordNotFound alone.
Rails already knows RecordNotFound is a 404: what rescue_from buys this app
Shows that Rails already maps RecordNotFound to 404, so this app's rescue_from supplies the page instead.
Two ways to fail: no handler matches, or the handler itself breaks
Covers an exception with no matching handler and one raised inside a handler, both reaching Rails' default handling.
Putting it together: the search algorithm in miniature
Reviews the full model, warns about rescuing StandardError, and ends with a small simulator of the search.