Skip to content

Instantly share code, notes, and snippets.

@yaauie
Last active December 20, 2015 13:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yaauie/6136288 to your computer and use it in GitHub Desktop.
Save yaauie/6136288 to your computer and use it in GitHub Desktop.

RFC: On handling exceptions whose constants may not be present

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
@steveklabnik
Copy link

Seems like the null object pattern, almost?

@yaauie
Copy link
Author

yaauie commented Aug 2, 2013

Almost, yeah.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment