Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to format ruby exception with backtrace into a string

Tags:

ruby

I have an exception e, and I would like to transform it into a string which is exactly the same as the standard ruby output on the stderr when the exception is uncaught.

Initial code gives me incorrect order of the stacktrace, and indentation is not correct.

Rather than writing my own code, I'd like to see some "oneliner". How do you do this?

like image 595
lzap Avatar asked Nov 09 '12 16:11

lzap


People also ask

What is exception backtrace?

Stack trace or backtrace is a sequential representation of the stack of method calls in a program which gets printed when an exception is raised. It is often used to find out the exact location in a program from where the exception was raised.

What is backtrace in Ruby?

The stack trace (usually named "backtrace" in Ruby, but also referred to as "stack backtrace" and "stack traceback") is a human-readable representation of the stack at a specific moment while running your program.

How do I ignore an error in Ruby?

To ignore errors in Ruby, add the following to your AppSignal configuration file. The ignore_errors value is an Array of Strings. ⚠️ Names set in ignore_errors will be matched on class name and not class inheritance.


1 Answers

This will be the same.

puts "#{[email protected]}: #{$!.message} (#{$!.class})", [email protected](1).map{|s| "\t#{s}"}

Or, using e:

puts "#{e.backtrace.first}: #{e.message} (#{e.class})", e.backtrace.drop(1).map{|s| "\t#{s}"}
like image 195
sawa Avatar answered Oct 09 '22 00:10

sawa