How can I handle errors with HTTParty?
An instance of HTTParty::Response has a code
attribute which contains the status code of the HTTP response. It's given as an integer. So, something like this:
response = HTTParty.get('http://twitter.com/statuses/public_timeline.json')
case response.code
when 200
puts "All good!"
when 404
puts "O noes not found!"
when 500...600
puts "ZOMG ERROR #{response.code}"
end
HTTParty doesn't print response
In fact, it parsed the body which is an empty string in this case. If you need other response information, it is accessible like so:
puts response.body, response.code, response.message, response.headers.inspect
Post Request Errors - Ruby and HTTParty
Debugged for a simpler post request, you have to be careful about sending/receiving json with ruby (you can run into trouble with conventional ajax approach when using html too). So its much easier to give it the most "agnostic" file format possible - text (or string), and the most generic key/value pair format, which I think is this: application/x-www-form-urlencoded
This finally gave me a valid 200 response in console (n.b. not my original request as a little bit more complex - but still "proof of concept"):
require "json"
require "httparty"
response = HTTParty.post("https://api.placeholder-uri",
{
:body => { :user => "placehodler-username", :password => "placeholder-password" }.to_json,
:headers => { "Content-Type" => "text", "Accept" => "application/x-www-form-urlencoded" }
})
puts response.body
puts response.code
puts response.message
Thanks to this ajax tutorial: https://www.airpair.com/js/jquery-ajax-post-tutorial for providing clue to solve this.
Related Topics
What's the Best Way to Talk to a Database While Using Sinatra
How to Specify a Required Switch (Not Argument) with Ruby Optionparser
(Ruby,Rails) Context of Self in Modules and Libraries...
Cannot Load Such File -- Readline (Loaderror) When Running Heroku Create --Stack Cedar
Write CSV in Ruby 1.9 and CSV::Writer
How to Override a Column in Rails Model
Error Running '_Rvm_Make Install'
Execute Ruby Code in Sublime Text 2
Can't Get Rack-Cors Working in Rails Application
Rbenv: Surviving Without Gemsets
How Mix in Routes in Sinatra for a Better Structure
Extracting the Last N Characters from a Ruby String
Why Does Accessing a Ssl Site with Mechanize on Windows Fail, But on MAC Work