dax
dax

Reputation: 11007

'on raise' hook in ruby

Is there a way to hook in some code after any raise is done in ruby? The idea is to provide some extra information about the error in a centralized location, such as follows:

def after_raise
  logger.error "some information here"
end

def logger
  @logger ||= Logger.new(my_log_output)
end

Edit: Maybe it will help if I'm more specific about what this is for.

I'm working a large project with multiple domains. There are times that raised errors are just not descriptive enough - today I was talking with one of my team-members and we discussed ways to work around this. It's not that the original raise messages are awful/completely nondescript (although, I'm sure that's the case in one or two places), just that as the project has evolved, new information has become useful for troubleshooting. We'd like to create something that can extend existing code.

Each domain is able to be tested alone, but plugs into an overall infrastructure. If we added this to the 'main' domain, when the application as a whole is running (for example, during end-to-end tests) this would be applied to all instances where raise is called. If we were testing a single domain, it would not apply.

Upvotes: 0

Views: 188

Answers (1)

August
August

Reputation: 12558

You can redefine the Kernel#raise method, keeping the original method through an alias:

module Kernel
  alias_method :_raise, :raise # original method is now _raise

  def raise(*args)
    # do hook stuff
    _raise(*args)
  end
end

Upvotes: 2

Related Questions