I recently submitted some very dirty code to mitigate the fact that some of the exceptions we need to handle aren't present on all systems. This isn't the first time I've come across it, and the solution I came up with looks rather terrible.
There must be a better way.
I'm about to write up a very simple gem that provides an interface for rescuing exceptions that may-or-may-not be present in the environment, and I could use a little help determining if this interface is agreeable:
begin
# code that may fail
rescue Exception::safe_resolve { Encoding::UndefinedConversionError },
Exception::safe_resolve { JSON::GeneratorError } => e
# handle caught exceptions
end
In this case, Exception::safe_resolve
would return either the
resolved object or a placeholder whose #===
always returned
false
:
class Exception
def self.safe_resolve
yield
rescue NameError
NullMatcher
end
module NullMatcher
extend self
def === (other)
false
end
end
end
Seems like the null object pattern, almost?