How to catch all errors in a class? - ruby

Here's what I'm trying to do:
class Foo
def foo
raise "lol noob"
end
# ... many other methods here ...
rescue StandardError => e
puts "error caught: #{e}"
end
Foo.new.foo
RuntimeError: lol noob
from (pry):45:in `foo'
As you can see, this does not work.
What I'm trying to avoid is to put a rescue block into every single method, given that they're many. Is it possible? If not, what's the best practice?

TL;DR
In Ruby, you generally have to wrap the caller with rescue, rather than the receiver.
Explanation
It's likely that you're finding this behavior surprising because you're not thinking of classes as executable code. A rescue clause in a class definition will capture exceptions raised while the class is being interpreted. Consider the following example:
class Foo
raise 'bar'
rescue
'Rescued!'
end
#=> "Rescued!"
Here, the rescue clause works because the exception is raised while the class code is executing. However, some Foo#bar method wouldn't normally get rescued by this clause (except possibly while being defined) because Foo is no longer the caller, it's the receiver.
A rescue clause on the class will catch exceptions raised when the class itself is being defined. However, to rescue within a method at run-time, you need to rescue within the caller (in this case, the #bar method) as follows:
class Foo
def bar
raise 'method exception'
rescue
'Rescued method exception.'
end
end
Foo.new.bar
#=> "Rescued method exception."

It would make no sense to have a common rescue block for a class, each method does different things right? How would you handle the variety of errors all in the same way? Error handling is just as much part of the logic as the "main" part of the method(s).
There's no silver bullet here, you rescue where you need to, and do what is needed when it is needed.
The Exceptional Ruby book may be of interest if you want to learn some common best practices.

If you're absolutely sure that the only error handling you need to do is log out errors, you can abstract away some of the repetitive error logging by defining a helper method that takes in a block and do your error handling there.
For example,
class Foo
def foo
handle_exception do
raise "lol noob"
end
end
def bar
handle_exception do
raise "rofl"
end
end
def handle_exception
yield
rescue => e
puts "error caught: #{e}"
end
end
Foo.new.foo # error caught: lol noob
Foo.new.bar # error caught: rofl
This has the benefit that later on you decide that want some alternate behavior, ie adding in a backtrace, you only have to touch one line of code:
def handle_exception
yield
rescue => e
puts "error caught: #{e}\n#{e.backtrace.join("\n")}"
end

Related

Why can't I send the class error further along with the chain?

I've got an error in some child class:
(byebug) e.class
CSV::MalformedCSVError
(byebug) e.message.truncate(150, omission: '')
"Illegal quoting in line 1. [SmarterCSV: csv line 1]"
(byebug) e
#<CSV::MalformedCSVError: Illegal quoting in line 1. [SmarterCSV: csv line 1]>
(byebug) raise e.class, e.message.truncate(150, omission: '')
*** ArgumentError Exception: wrong number of arguments (given 1, expected 2)
I want to send the original error class and message to a further class, to rescue all of them without the creation of custom error for each child class (ChildClassError = Class.new(StandardError)).
I will be grateful for the help. I would like to understand the reason.
What's wrong here?
rescue StandardError => e
raise e.class
end
*** ArgumentError Exception: wrong number of arguments (given 0, expected 2)
The issue is with CSV::MalformedCSVError#new violating the standard for the exceptions that Kernel#raise expects.
The latter attempts to call Exception#new/1 while the only possible arity of the constructor of CSV::MalformedCSVError is two. You should create an object yourself:
raise CSV::MalformedCSVError.new(e.message.truncate(150, omission: ''), __LINE__)
For the generic case, you probably should get the arity of the constructor and behave correspondingly.
You could do so by just rescuing from StandardError exception like so:
class Foo
attr_reader :value
def initialize(value)
#value = value
end
end
begin
foo = Foo.new
rescue StandardError => e
raise e.class.new(e.message.truncate(150, omission: ''))
end
Though this way, you're reinitializing another object of the same class here with a new/modified message.
Edit: Aleksei made a good point on arity, as a custom error/exception classes are made differently to have fine-grained control over the exceptions that are helpful while debugging. Make sure you have the right arity otherwise you'd be on a goose hunt than solving actual problem.

Catching exceptions while using an external gem

I have written a program that utilizes an external ruby gem. As I am doing a lot of different actions with this, I want to be able to rescue and handle exceptions across the board, instead of implementing it each time I call a method.
What is the best way to do this?
Should I write my own method that simply calls the external gem and also rescues exceptions? Or is there another way to do something like "Whenever an exception of this type comes up anywhere in the program, handle it this way"?
I know that if I wrote the external gem code I could add error handling like that, but that is not feasible.
The basic answer to this is probably to wrap the class you're working with; Ruby allows for a lot of flexibility for doing this since it has method_missing and a pretty dynamic class environment. Here's an example (which may or may not be fatally flawed, but demonstrates the principle:
# A Foo class that throws a nasty exception somewhere.
class Foo
class SpecialException < Exception; end
def bar
raise SpecialException.new("Barf!")
end
end
# This will rescue all exceptions and optionally call a callback instead
# of raising.
class RescueAllTheThings
def initialize(instance, callback=nil)
#instance = instance
#callback = callback
end
def method_missing(method, *args, &block)
if #instance.respond_to? method
begin
#instance.send(method, *args, &block)
rescue Exception => e
#callback.call(e) if #callback
end
else
super
end
end
end
# A normal non-wrapped Foo. Exceptions will propagate.
raw_foo = Foo.new
# We'll wrap it here with a rescue so that we don't exit when it raises.
begin
raw_foo.bar
rescue Foo::SpecialException
puts "Uncaught exception here! I would've exited without this local rescue!"
end
# Wrap the raw_foo instance with RescueAllTheThings, which will pass through
# all method calls, but will rescue all exceptions and optionally call the
# callback instead. Using lambda{} is a fancy way to create a temporary class
# with a #call method that runs the block of code passed. This code is executed
# in the context *here*, so local variables etc. are usable from wherever the
# lambda is placed.
safe_foo = RescueAllTheThings.new(raw_foo, lambda { |e| puts "Caught an exception: #{e.class}: #{e.message}" })
# No need to rescue anything, it's all handled!
safe_foo.bar
puts "Look ma, I didn't exit!"
Whether it makes sense to use a very generic version of a wrapper class, such as the RescueAllTheThings class above, or something more specific to the thing you're trying to wrap will depend a lot on the context and the specific issues you're looking to solve.

Rescue given anonymous module instead of exception class

We can put a class or module after a rescue statement, but in the code below, I see a method following rescue, which does not fit into this pattern. How is it working and how is it producing the output it has been designed to show?
def errors_with_message(pattern)
# Generate an anonymous "matcher module" with a custom threequals
m = Module.new
(class << m; self; end).instance_eval do
define_method(:===) do |e|
pattern === e.message
end
end
m
end
puts "About to raise"
begin
raise "Timeout while reading from socket"
rescue errors_with_message(/socket/)
puts "Ignoring socket error"
end
puts "Continuing..."
Output
About to raise
Ignoring socket error
Continuing...
Rescue requires a class or a module, true. So, that method creates an anonymous module with special behaviour. You see, when rescue searches for a handler, it applies === operator to exception classes/modules you provided, passing as an argument the actual exception.
begin
# do something
rescue MyCustomError
# process your error
rescue StandardError
# process standard error
end
So, if StandardError (or one of its descendants) was raised, the first handler will be skipped and second handler will be matched.
Now, the module from errors_with_message is special. It redefines threequals operator to match on exception message. So, if an error was raised and its message contains word "socket", this handler will match. Cool trick, huh?

Raising an exception: use instance or class?

I have seen Ruby code that raises exceptions using a class:
raise GoatException, "Maximum of 3 goats per bumper car."
Other code uses an instance:
raise GoatException.new "No leotard found suitable for goat."
Both of these are rescued the same way. Is there any reason to use an instance vs a class?
It makes no difference; the exception class will be instiantiated in either case.
If you provide a string, either as the argument to new or as the second argument to raise, it be passed to initialize and will become the exception instance's .message.
For example:
class GoatException < StandardError
def initialize(message)
puts "initializing with message: #{message}"
super
end
end
begin
raise GoatException.new "Goats do not enjoy origami." #--|
# | Equivilents
raise GoatException, "Goats do not enjoy origami." #--|
rescue Exception => e
puts "Goat exception! The class is '#{e.class}'. Message is '#{e.message}'"
end
If you comment the first raise above, you'll see that:
In both cases, initialize is called.
In both cases, the exception class is GoatException, not class as it would be if we were rescuing the exception class itself.

Ruby: Unwanted context in exceptions raised within an eval

There seems to be an odd discrepancy between the messages contained in Ruby Exceptions raised directly and raised from within evals. For instance, the following code:
def foo
raise "Help!"
end
puts "\nRescue foo"
begin
foo
rescue RuntimeError => e
puts e.message
end
puts "\nRescue eval 'foo'"
begin
eval "foo"
rescue RuntimeError => e
puts e.message
end
Produces the following output:
Rescue foo
Help!
Rescue eval 'foo'
./temp.rb:2:in `foo': Help!
Short of using regexps to sub it out, is there any way I can raise the exception without the context in the second case?
Thanks. I was defining my own error anyway, so that's an easy fix.
I've made a slight change, so that the superclass is initialized as well:
class MyException < RuntimeError
attr_accessor :my_message
def initialize(m)
#my_message = String.new(m)
super
end
end
(the String.new call seems to be needed to avoid getting the old behaviour again; presumably Exception.new modifies the message in-place.)
That is unusual, I've not come across that before. I can't see a way of persuading eval not to add that information, so either you do the regexp munging you mentioned, or you can define your own error type:
class MyError < RuntimeError
attr_accessor :my_message
def initialize(m)
#my_message = m.dup
super
end
end
def foo
raise MyError.new("Help!")
end
puts "\nRescue eval 'foo'"
begin
eval "foo"
rescue RuntimeError => e
puts e.my_message
end
With output:
Rescue eval 'foo'
Help!
In anything larger than a simple script, defining your own error types is good practice anyway.
(updated to fix code in line with what Chris said in his answer)

Resources