Outputting errors in a rescue (Ruby/Rails)

Ruby on-RailsRubyException

Ruby on-Rails Problem Overview


Just a quick question. I cant find it in the documentation.

If I use a standard begin ... rescue, how do I print all the errors or stack trace into the rescue?

e.g.:

begin 
    do x
rescue
    puts errors
end

Any ideas?

Ruby on-Rails Solutions


Solution 1 - Ruby on-Rails

There are at least two ways that I know of to get the error. The first is using a global variable: $! which is always set to the last error that occurred. The second is by explicitly capturing the error when you rescue:

begin
  # do something that fails...
rescue => error
  # error and $! are equivalent here
end

Either one will let you inspect or print out the backtrace using either:

$!.backtrace # => array of backtrace steps
error.backtrace # => same error

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionovertoneView Question on Stackoverflow
Solution 1 - Ruby on-RailsPeter BrownView Answer on Stackoverflow