Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get caller's caller for Ruby exception

Right now our application is running on Heroku, and in order to save restarts and possible latency the application is designed to cache all errors and send them to stderr and just server a stale cache until the issue is resolved by another push. This prevents application takedown...

However, the logs keep filling up excessively with entire traces which we don't want, so I built a little snippet (that is partially stolen from Rails) to parse caller and only send that line, however with errors being sent from a rescue, we get the wrong line so I was wondering how I could get the caller or the caller or if there was a better way to handle this situation. Here is the snippet:

module StdErr
  def error(message)
    file = 'Unknown'
    line = '0'

    if /^(.+?):(\d+)(?::in `(.*)')?/ =~ caller[1]
      file = $1
      line = $2
    end

    $stderr.puts "ERROR: #{message} on line #{line} of #{file}"
  end
end
like image 818
Jordon Bedwell Avatar asked Sep 09 '26 22:09

Jordon Bedwell


2 Answers

If I get it, you want to raise a exception with a backtrace that begins on the caller of the caller. Do it:

def raise_cc(*args)
  raise(*args)
rescue Exception
  # Raises the same exception, removing the last 2 items
  # from backtrace (this method and its caller). The first
  # will be the caller of the caller of this method.
  raise($!.class, $!.message, $!.backtrace[2..(-1)])
end
like image 105
Guilherme Bernal Avatar answered Sep 13 '26 01:09

Guilherme Bernal


caller returns an array and you can go deeper into the call stack by looking at it's later elements (note that you're looking at caller[1])

like image 20
Paweł Obrok Avatar answered Sep 13 '26 00:09

Paweł Obrok