lzap
lzap

Reputation: 17174

How to format ruby exception with backtrace into a string

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?

Upvotes: 13

Views: 5766

Answers (3)

Meredith
Meredith

Reputation: 4454

I am guessing this was not possible before Ruby 2, but this is now a function in core:

e.full_message

If you don't want color codes in the output:

e.full_message(highlight: false)

https://ruby-doc.org/core-2.5.1/Exception.html#method-i-full_message

Upvotes: 2

akostadinov
akostadinov

Reputation: 18614

If you want to log as a single string, not just output, you can do like this:

puts "#{e.backtrace.first}: #{e.message} (#{e.class})\n\t" + e.backtrace.join("\n\t")

Upvotes: 0

sawa
sawa

Reputation: 168101

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}"}

Upvotes: 20

Related Questions