简体   繁体   English

如何处理httparty错误导轨

[英]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? 我正在将一些api与httparty gem一起使用,我已经阅读了以下问题: 如何处理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. 无论如何,这实际上取决于您正在编写的代码,这是一个有意见的问题,但就我个人的个人喜好而言,处理异常和错误代码并不是过分谨慎,而是可以防止将来发生故障。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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