post

Raising custom exceptions in Rails
Raising custom exceptions in Rails

I’ve grown to not like the if/else block at all. Here’s an example of what I’m not fond of:

def do_some_work
  unless feeling_lazy?
    if current_user.is_boss
      do_boss_work
    else
      do_work
    end
    flash[:notice] = "Glad you're working hard."
  else
    redirect_to lazy_page_path
    flash[:error] = "You're too lazy to work here."
  end
end

The if/else statements just clutter the code. It disguises the logic by its ugliness. When appropriate, I’ll avoid if/else by raising exceptions to handle the “else” condition. That way, I can assume everything works how I want it to, and just raise if it doesn’t. Something like this is much better, in my opinion…

def do_some_work
  raise if feeling_lazy?
  current_user.is_boss ? do_boss_work : do_work
  flash[:notice] = "Glad you're working hard."
rescue
  redirect_to lazy_page_path
  flash[:error] = "You're too lazy to work here."
end

That’s much easier on the eyes. But I like to raise application-specific exceptions instead of the generic “rescue everything” solution. The way I’m currently doing this feels a little, I don’t know, sloppy. What I usually do is put a separate module in the lib folder, then include it in ApplicationController so it’s available everywhere. Something like this:

# lib/exceptions.rb
module Exceptions
  class TooLazyToWork < StandardError; end
  class NotTheBoss < StandardError; end
end

# using the custom exceptions
def do_some_work
  raise Exceptions::TooLazyToWork if feeling_lazy?
  ...
rescue Exceptions::TooLazyToWork => exception
  flash[:error] = "You can't work: #{exception.message}"
end

I’m not doing anything with the class except inheriting from StandardError (or Error, RunTimeError, etc)—that’s what feels sloppy. Is there a better way to achieve this? If you notice something that could be (or should be) done better (or differently), I’d appreciate the advice.

Comments
01
22 Aug 2007 05:53 AM

I use the same approach … I just wanted to note that you can save your self some typing by adding include Exceptions to the controller, and just do:

raise TooLazyToWork
02
22 Aug 2007 08:23 AM

Alright, thanks… I actually am including the module in the corresponding controllers, I just left that part out.




Please rewrite the image text in the SPAM field: Spam Protection

Preview

2008 by Ryan Heath | Get In Touch

flickr

DesolateInfinityLooking upDazedBlurred