简体   繁体   中英

How to handle httparty errors rails

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM