1

I am using some api with httparty gem I have read this question: How can I handle errors with HTTParty?

And there are two most upvoted answers how to handle errors first one using response codes (which does not address connection failures)

 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

And the second - catching errors.

 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

So what is the best practice do handle errors? Do I need to handle connection failures? Right now I am thinking of combining this two approaches like this:

 begin
    response = HTTParty.get(url)

    case response.code
    when 200
      # do something
    when 404
      # show error
    end

    rescue HTTParty::Error => error
      puts error.inspect
    rescue => error
      puts error.inspect
    end
 end

Is it a good approach to handle both connection error and response codes? Or I am being to overcautious?

cdpalmer
  • 658
  • 1
  • 7
  • 19
user2950593
  • 9,233
  • 15
  • 67
  • 131
  • I'd recommend against the second `rescue => error` clause depending on the application. Catching all errors is generally bad practice, since it can swallow unexpected errors that only show up later in more unexpected ways. – Cameron Gagnon Jun 16 '20 at 00:25

1 Answers1

3

You definitely want to handle connection errors are they are exceptions outside the normal flow of your code, hence the name exceptions. These exceptions happen when connections timeout, connections are unreachable, etc, and handling them ensures your code is resilient to these types of failures.

As far as response codes, I would highly suggest you handle edge cases, or error response codes, so that your code is aware when there are things such as pages not found or bad requests which don't trigger exceptions.

In any case, it really depends on the code that you're writing and at this point is a matter of opinion but in my opinion and personal coding preference, handling both exceptions and error codes is not being overcautious but rather preventing future failures.

Leo Correa
  • 19,131
  • 2
  • 53
  • 71