Topic: DRY Exception handling at the application level

Hi Everybody,

  I made a mini-discovery today and I thought that I'd share it with you all.
I figured out how to handle errors at the application level in a very DRY way using the key word yield.  The basic strategy is to have an exception handling function that all of your other functions in the controller may pass their body's code block to.  This prevents repeating your rescue statements, and has the extra added bonus of using the Ruby keyword "yield."

*** IN controller ***

def handle_error
  yield # Your other action's code is executed here and rescued below.
  rescue LoginFailureException
   flash[:notice] = "Bozooka!"
   redirect_to :action => "spanking"
  rescue YourCustomException
   flash[:notice] = "Refrain from farting, please."
   redirect_to :action => "spanking"

def any_action
    # this block is passed to handle_error function

Hope this helps somebody. smile

Re: DRY Exception handling at the application level

Why doesn't rescue_action_in_public do the trick for you? Do you handle all errors as exceptions? My suggestion is that you treat errors (things you expect to go wrong during program execution) locally, and only let completely unanticipated exceptions bubble up to the top.

The rationale is that you know more about the implications of a given negative result at the most local level, making that the best place for your code to decide how best to proceed. An exception that makes it to the top is the semantic equivalent of "500 Server Error!". That's where rescue_action_in_public helps out: It lets you put a nice face on an ugly situation. You can present a nice "we couldn't fetch the page you requested" screen without confessing that you have no idea what went wrong smile

Look at Jamis Buck's exception_notifier plugin as an alternative to rescue_action_in_public. It totally rocks and it even sends you an email with complete details when things go way wrong.