New Error Handling in Rails 2.0

Dec 13, 2007

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 


and now with the new exception handling:

class AccountsController  :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

Hi, I'm Glenn! 👋 I've spent most of my career working with or at startups. I'm currently the Director of Product @ Ockam where I'm helping developers build applications and systems that are secure-by-design. It's time we started securely connecting apps, not networks.

Previously I led the Terraform product team @ HashiCorp, where we launched Terraform Cloud and set the stage for a successful IPO. Prior to that I was part of the Startup Team @ AWS, and earlier still an early employee @ Heroku. I've also invested in a couple of dozen early stage startups.