Reputation: 17174
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
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
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
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