Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to display error type in ruby?

Tags:

exception

ruby

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 
like image 910
Fluffy Avatar asked Sep 22 '09 17:09

Fluffy


People also ask

How do I raise error messages in Ruby?

Ruby actually gives you the power to manually raise exceptions yourself by calling Kernel#raise. This allows you to choose what type of exception to raise and even set your own error message. If you do not specify what type of exception to raise, Ruby will default to RuntimeError (a subclass of StandardError ).

Does Ruby have try catch?

In Ruby we have a way to deal with these cases, we have begin, end(default try catch) and we can use try and catch, both try catch and raise rescue used for the same purpose, one will throw exception(throw or raise) with any specific name inside another(catch or rescue).

What is a Ruby error?

Exceptions are Ruby's way of dealing with unexpected events. If you've ever made a typo in your code, causing your program to crash with a message like SyntaxError or NoMethodError , then you've seen exceptions in action. When you raise an exception in Ruby, the world stops and your program starts to shut down.


2 Answers

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

like image 135
sepp2k Avatar answered Oct 05 '22 02:10

sepp2k


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 
like image 31
Ulysse BN Avatar answered Oct 05 '22 02:10

Ulysse BN