côdeazur brasil blog

Archive for the ‘Rails’ Category

New Exception Handling in Rails 2.0

Color me stupid but I’ve no clue on why, since Rails 2.o is all about RESTful goodness, all of the HTTP error codes are not valid ActionController Exceptions to begin with.

I’m looking around and finding it pretty unattractive the way people deal with sending out the status headers right in the code without any clue to what is really happening.

Luckily, if “403 Forbidden” is not a valid Exception, for instance, Rails 2.0 comes with a much easier way to deal with Exceptions as a whole. I’m finding it so much more elegant to raise Exceptions whenever I need them and letting my code deal with sending the right headers somewhere else.

To create an application-wide Forbidden Exception, you would:

class Forbidden < StandardError
end

class ApplicationController < ActionController::Base
   rescue_from Forbidden, :with => :forbidden

   def forbidden
      head :forbidden
   end

   def can_modify?(obj)
      if obj.owner == current_user
         yield
      else
         raise Forbidden
      end
   end

end

You don’t really have to do this in the application.rb (I reckon if you’re not purely dealing with a RESTful webservice, it could add quite the clutter to your main Controller), but you can even have a sort of RescueController and have it deal with your Exceptions for you.

Either way, just the fact that you’re raising an Exception when something bad happens is much more elegant than just writing out the right HTTP header, imo.