38

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
Fluffy
  • 27,504
  • 41
  • 151
  • 234

3 Answers3

77
begin
  raise ArgumentError, "I'm a description"
rescue => e
  puts "An error of type #{e.class} happened, message is #{e.message}"
end

Prints: An error of type ArgumentError happened, message is I'm a description

Ulysse BN
  • 10,116
  • 7
  • 54
  • 82
sepp2k
  • 363,768
  • 54
  • 674
  • 675
  • 3
    And then if you still need specific handling for different types of errors, you can do that with a case..when. – cpm Sep 22 '09 at 17:44
  • 11
    Watch it, do not catch Exception unless you are completely aware of what it implies. Use rescue => ex instead(Convention over configuration) As a default cacher. – Fabián Heredia Montiel Jul 19 '14 at 03:00
7

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
Ulysse BN
  • 10,116
  • 7
  • 54
  • 82
  • `full_message` came on board in Rails 6. Not present in Rails 5. – David Hempy Oct 09 '20 at 15:41
  • 1
    @DavidHempy I'm refering at the ruby method `full_message`, not rails. Take a look at the link ! It looks like it came into ruby in the `2.5` – Ulysse BN Oct 09 '20 at 16:30
  • Ack...my bad. You're right, @Ulysse BN . (We're on Ruby 2.4 / Rails 5.2. Most of my modern disappointments are from my Rails version, not the Ruby version) – David Hempy Oct 09 '20 at 17:15
5

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