Effectively using rescue_from

Norbert Crombach

This article is left here for historical purposes, please read the comments carefully after you’ve read the article.

Even though Ryan Daigle already covered it in his usual timely fashion, I’d like to share some real life examples of how we use the relatively new rescue_from functionality.

Because I usually prefer methods that raise exceptions instead of returning a boolean, like, say, save! instead of just save, I thought it would be nice if I could deal with some common exceptions on a higher level. This lead me to write a Rails patch based on the exception_handler plugin, which I previously used in some projects.

A few weeks later the patch found its way into Rails core, just in time for the 2.0 preview release. Now everybody can rewrite this:
class PostsController < ApplicationController
  def create
    @post = Post.create!(params[:post])
  rescue ActiveRecord::RecordInvalid
    render :action => :new

  def update
    @post = Post.find(params[:id])
  rescue ActiveRecord::RecordInvalid
    render :action => :edit
to something like this:
class ApplicationController < ActionController::Base
  rescue_from ActiveRecord::RecordInvalid do |exception|
    render :action => (exception.record.new_record? ? :new : :edit)

class PostsController < ApplicationController def create @post = Post.create!(params[:post]) end def update @post = Post.find(params[:id]) @post.update_attributes!(params[:post]) end end

And it just works.