Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Outputting errors in a rescue (Ruby/Rails)

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?

like image 643
overtone Avatar asked Sep 01 '11 12:09

overtone


People also ask

What happens if in a begin rescue block the rescue code has an error?

The code between “begin” and “rescue” is where a probable exception might occur. If an exception occurs, the rescue block will execute. You should try to be specific about what exception you're rescuing because it's considered a bad practice to capture all exceptions.

How do you rescue all exceptions in Ruby?

A raised exception can be rescued to prevent it from crashing your application once it reaches the top of the call stack. In Ruby, we use the rescue keyword for that. When rescuing an exception in Ruby, you can specify a specific error class that should be rescued from.

How do you handle exceptions in Rails?

Exception handling in Ruby on Rails is similar to exception handling in Ruby. Which means, we enclose the code that could raise an exception in a begin/end block and use rescue clauses to tell Ruby the types of exceptions we want to handle.

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).


1 Answers

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 
like image 100
Peter Brown Avatar answered Sep 21 '22 10:09

Peter Brown