Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I handle errors with HTTParty?

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.

like image 609
preethinarayan Avatar asked Oct 26 '11 22:10

preethinarayan


2 Answers

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 
like image 195
Jordan Running Avatar answered Sep 28 '22 10:09

Jordan Running


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

like image 26
mklb Avatar answered Sep 28 '22 12:09

mklb