Skip to content

Instantly share code, notes, and snippets.

@therealadam
Created January 17, 2012 15:27
Show Gist options
  • Save therealadam/1627058 to your computer and use it in GitHub Desktop.
Save therealadam/1627058 to your computer and use it in GitHub Desktop.
Sugar for swallowing exceptions
# 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