New Error Handling in Rails 2.0

Posted by glenn on Thursday, December 13, 2007

Posted in rubyonrails, errors

error-handling

Rails 2.0 has added in a very cool way to trap errors without a bunch of messy nested rescue blocks or case statements.

The ticket that added all the magic is here. And it couldn't come too soon as I immediately had a project that needed it. Check out what I was looking at doing:

class AccountsController < ActionController::Base

  def rescue_action_in_public(exception)
    case exception
      when Account::Overdrawn
        flash[:error] = "Sorry the account this transaction would make this account overdrawn" 
        redirect_to account_path(params[:account])
      when Account::Suspended
        flash[:error] = "Sorry the account you are trying to use has been suspended, please contact customer services" 
        redirect_to account_path(params[:account])
      when ActiveRecord::RecordNotFound
        flash[:error] = "No such account could be found" 
        redirect_to user_path(current_user)
      else
        super
    end
  end
end

and now with the new exception handling:

class AccountsController < ActionController::Base
  rescue_from Account::Overdrawn, :with => :overdrawn
  rescue_from Account::Suspended, :with => :suspended
  rescue_from ActiveRecord::RecordNotFound, :with => :not_found

  protected
    def overdrawn
      flash[:error] = "Sorry the account this transaction would make this account overdrawn" 
      redirect_to account_path(params[:account])
    end

    def suspended
      flash[:error] = "Sorry the account you are trying to use has been suspended, please contact customer services" 
      redirect_to account_path(params[:account])
    end

    def not_found
      flash[:error] = "No such account could be found" 
      redirect_to user_path(current_user)
    end
end

woohoo!! Much cleaner and more descriptive of my intentions

Glenn Gillen is a ruby and ruby on rails developer with clients in London, New York, Los Angeles, and Australia. Ruby Pond specialise in social networking development, and social and online marketing. Contact Ruby Pond if you wish to discuss hiring Glenn or one of our other developers for your own project.
blog comments powered by Disqus