How to display error type in ruby?

Viewed 44525

in the following code

begin
 raise StandardError, 'message'
 #some code that raises a lot of exception
rescue StandardError
 #handle error
rescue OtherError
 #handle error
rescue YetAnotherError
 #handle error
end

I want to print a warning stating the type and the message of the error without adding print statement to each of the rescue clauses, like

begin
 raise StandardError, 'message'
 #some code that raises a lot of exception
rescue StandardError
 #handle error
rescue OtherError
 #handle error
rescue YetAnotherError
 #handle error
???
 print "An error of type #{???} happened, message is #{???}"
end
3 Answers

If you want to show the original backtrace and highlighting, you can take advantage of Exception#full_message:

full_message(highlight: bool, order: [:top or :bottom]) → string

Returns formatted string of exception. The returned string is formatted using the same format that Ruby uses when printing an uncaught exceptions to stderr.

If highlight is true the default error handler will send the messages to a tty.

order must be either of :top or :bottom, and places the error message and the innermost backtrace come at the top or the bottom.

The default values of these options depend on $stderr and its tty? at the timing of a call.

begin
  raise ArgumentError, "I'm a description"
rescue StandardError => e
  puts e.full_message(highlight: true, order: :top)
end

My version of printing errors with type, message and trace:

begin
    some_statement
rescue => e
    puts "Exception Occurred #{e.class}. Message: #{e.message}. Backtrace:  \n #{e.backtrace.join("\n")}"
    Rails.logger.error "Exception Occurred #{e.class}. Message: #{e.message}. Backtrace:  \n #{e.backtrace.join("\n")}"
end
Related