views:

28

answers:

2

could someone explain the code in catch_exceptions?

i have difficulties to understand.

thanks

class ApplicationController < ActionController::Base
  around_filter :catch_exceptions

  private

  def catch_exceptions
    yield
  rescue => exception
    logger.debug "Caught exception! #{exception}"
    raise
  end
end
+2  A: 

Simple.

You need first to understand the concept of the around_filter. It puts something AROUND a method call. Also you need to understand YIELD, that is executing a block.

so if you have something like an Index action.

def index # run code run end

that means it will be sent as a block to that around_filter, which will execute that just as if it were...

  def catch_exceptions
    def index
      #run code run
    end
  rescue => exception
    logger.debug "Caught exception! #{exception}"
    raise
  end
Rodrigo Dellacqua
+1  A: 

catch_exceptions is a method that takes a block. You can tell because it contains a yield (which executes the passed in block).

The method is catching any exception that occurs in that block, logging them, then re-throwing them so other code can catch it too.

The 'around_filter' line makes rails pass each controller method that would be executed to the catch_exceptions method instead.

The overall result is that all exceptions thrown by controller methods get logged.

Nigel Thorne