Created
November 3, 2011 17:33
-
-
Save scottwater/1337132 to your computer and use it in GitHub Desktop.
Thoughts on how to properly handle exceptions in a web service request?
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
| require 'httparty' | |
| require 'crack' | |
| class KickoffLabsAPI | |
| include HTTParty | |
| base_uri 'http://api.kickofflabs.com' | |
| def self.subscribe(page_id, args={}) | |
| response = post("/v1/#{page_id}/subscribe", :body => args) | |
| if response.code == 200 | |
| Crack::JSON.parse(response.body) | |
| else | |
| "Failed with status #{response.code} and body #{response.body}" | |
| end | |
| end | |
| def self.info(page_id, args={}) | |
| response = get("/v1/#{page_id}/info", :query => args) | |
| if response.code == 200 | |
| Crack::JSON.parse(response.body) | |
| else | |
| "Failed with status #{response.code} and body #{response.body}" | |
| end | |
| end | |
| end |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
More details:
While this is just an example, I do want to publish something that is a little cleaner.
The API will return a 404 if the landing page does not exist and a 409 on subscribe if the email is not valid. Obviously returning a string is not ideal. :)
However, if I simply return nil, then you don't really get why it failed...but raising an exception seems off as well.
Thanks!