never_had_a_name
never_had_a_name

Reputation: 93296

ruby on rails 3 question

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

Upvotes: 0

Views: 990

Answers (2)

Rodrigo Dellacqua
Rodrigo Dellacqua

Reputation: 268

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

Upvotes: 4

Nigel Thorne
Nigel Thorne

Reputation: 21558

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.

Upvotes: 1

Related Questions