How to Handle Errors with Httparty

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



Leave a reply



Submit