How can I handle errors with HTTParty?

Ruby on-RailsRubyHttparty

Ruby on-Rails Problem Overview


I'm working on a Rails application using HTTParty to make HTTP requests. How can I handle HTTP errors with HTTParty? Specifically, I need to catch HTTP 502 & 503 and other errors like connection refused and timeout errors.

Ruby on-Rails Solutions


Solution 1 - Ruby on-Rails

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

Solution 2 - Ruby on-Rails

This answer addresses connection failures. If a URL isn´t found the status code won´t help you. Rescue it like this:

 begin
   HTTParty.get('http://google.com')
 rescue HTTParty::Error
   # don´t do anything / whatever
 rescue StandardError
   # rescue instances of StandardError,
   # i.e. Timeout::Error, SocketError etc
 end

For more information see: this github issue

Solution 3 - Ruby on-Rails

You can also use such handy predicate methods as success? or bad_gateway? in this way:

response = HTTParty.post(uri, options)
p response.success?

Full list of possible responses can be found under Rack::Utils::SYMBOL_TO_STATUS_CODE constant.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionpreethinarayanView Question on Stackoverflow
Solution 1 - Ruby on-RailsJordan RunningView Answer on Stackoverflow
Solution 2 - Ruby on-RailsmklbView Answer on Stackoverflow
Solution 3 - Ruby on-RailsArturView Answer on Stackoverflow