How can I handle errors using HTTParty?

I am working on a Rails application using HTTParty to create HTTP requests. How can I handle HTTP errors using HTTParty? In particular, I need to catch HTTP 502 and 503 and other errors, such as connection failure and timeout.

+54
ruby ruby-on-rails
Oct 26 '11 at 10:15
source share
3 answers

The HTTParty :: Response instance has a code attribute that contains the HTTP response status code. It is 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 
+73
Oct. 26 2018-11-22T00:
source

This answer relates to connection failures. If the URL is not found, the status code will not help you. Save him like this:

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

See this github issue for more info.

+18
Nov 05 '14 at 22:08
source

You can also use convenient predicate methods like success? or bad_gateway? in the following way:

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

A complete list of possible answers can be found in the constant Net::HTTPResponse::CODE_TO_OBJ .

+8
Jun 22 '16 at 3:17
source



All Articles