Skip to content

Instantly share code, notes, and snippets.

@kristopherjohnson
Last active October 17, 2018 14:04
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kristopherjohnson/e650487a5dc0ce9dd24ea2584db63e18 to your computer and use it in GitHub Desktop.
Save kristopherjohnson/e650487a5dc0ce9dd24ea2584db63e18 to your computer and use it in GitHub Desktop.
Ruby: Pretty-printed exception backtrace
# Generate a backtrace string for given exception.
# Generated string is a series of lines, each beginning with a tab and "at ".
def pretty_backtrace(exception)
"\tat #{exception.backtrace.join("\n\tat ")}"
end
# Generate a string containing exception message followed by backtrace.
def pretty_exception(exception)
"#{exception.message}\n#{pretty_backtrace(exception)}"
end
@kristopherjohnson
Copy link
Author

kristopherjohnson commented May 25, 2016

Example uses:

begin
  do_something
rescue => e
  STDERR.puts "Exception: #{e.message}"
  STDERR.puts "Backtrace:\n#{pretty_backtrace(e)}\n"
end
begin
  do_something
rescue => e
  STDERR.puts "Error: #{pretty_exception(e)}\n"
end

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment