Luigi
Luigi

Reputation: 5603

Alternative to "rescue Exception"

I get some unexpected errors on occasion such as timeout errors, 503 errors, etc. There are errors that I don't even know about that I may receive. I can't account for all of them by doing something like:

rescue Timeout::Error => e

It's also a terrible idea to rescue Exception.

What is an alternative that I could use? I want my code to rescue all of them when there is an error; if there is no error, I need it to be avoided. I want to be able to kill my script but not skip over syntax errors, etc.

Upvotes: 1

Views: 324

Answers (1)

fotanus
fotanus

Reputation: 20106

You can rescue for StandardError, or simply rescue, which are the same:

rescue StandardError => e
# or
rescue => e

You can see in the following table which exceptions are rescued from StandardError - Note that they are a subset from Exception, and conceitually should be errors that are OK to be catch.

Of course you can have gems that defines exception in the wrong place, but this should not happen in well-developed gems.

ruby exceptions
(source: rubylearning.com)

I personally like to rescue only exceptions I know how to handle, except when it is to add in a log/backtrace system to consult the errors later. If this is the case, I usually rescue StandardError

Upvotes: 6

Related Questions