Created
January 17, 2012 15:27
-
-
Save therealadam/1627058 to your computer and use it in GitHub Desktop.
Sugar for swallowing exceptions
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Suppose we're going to have a bunch of code like the following | |
# boilerplate (ignore the unfortunate nil propagation) | |
@city = begin | |
GizmoStore::Thingy.get(123) | |
rescue GizmoStore::NotFound | |
nil | |
end | |
# I can't decide if this is useful boilerplate elimination or | |
# saccharine ivory tower abstraction. | |
@language = swallow(GizmoStore::NotFound) do | |
GizmoStore::Thingy.get(123) | |
end | |
def swallow(ex, &block) | |
begin | |
block.call | |
rescue => exception | |
if exception.is_a?(ex) | |
nil | |
else | |
raise ex | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment