A full backtrace for a Ruby Exception

When your Ruby code dumps an exception, it can be useful to see a full backtrace instead of the truncated view that Ruby gives you by default.

One way to do this is to wrap the offending code in a begin - rescue - end block to catch the exception, outpit a full backtrace, and re-raise the exception:

  # your code that raises an exception goes here!
rescue => e
  puts "Exception: #{$!}"
  puts caller
  raise e

Note, we're rescuing the StandardError class of exceptions. Know what you're rescuing. Read more here and here.

The $! variable contains the error message for the caught exception. An alternative way of writing this line is

puts "Exception: #{e.message}"

You can omit the call to raise if you don't want the exception to stop execution, and an alternative to using caller is shown below:

  puts "Backtrace:\n\t#{e.backtrace.join("\n\t")}"