How to display error type in ruby?
Solution 1
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
Solution 2
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
Solution 3
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 itstty?
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
Comments
-
Fluffy over 3 years
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