Skip to content

Instantly share code, notes, and snippets.

@SViccari
Last active December 5, 2018 16:07
Show Gist options
  • Save SViccari/4f1090bee62518d6cbf7f68dabf0d09d to your computer and use it in GitHub Desktop.
Save SViccari/4f1090bee62518d6cbf7f68dabf0d09d to your computer and use it in GitHub Desktop.
Gem API Wrapper - To Raise or Not To Raise
# example of working with a gem that always returns a response object
class Account
def find(account_id)
response = Hubspot::Account.find(account_id)
handle_response(response)
end
private
def handle_response(response)
if response.success?
response.data
else
MissingAccount.new
end
end
end
# pros
# - The design makes it more obvious to handle error cases
# - Errors are part of the return value, not an exception
# - favors conditionals over rescuing
# cons
# - requires the gem user to follow each API call with `response.success?; response.data`
# - less idiomatic in the Ruby community as all other API wrappers raise when a request returns an error
# example of working with a gem that raises for any non-200 request
class Account
def find(account_id)
Hubspot::Account.find(account_id)
rescue Hubspot::NotFound => exception
MissingAccount.new
end
end
# pros
# - this design doesn't require "success?" checks for threading data
# example:
# contact = Hubspot::Contact.create(name: "joey")
# contact_list = Hubspot::ContactList.create(name: "friends")
# Hubspot::ContactList.add(contact)
# cons
# - gem consumers may forget to rescue an API call, resulting in an exception
# - encourages/requires gem users to wrap API calls in a rescue
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment