ruby - 处理来自 Net::HTTP 的异常的最佳方法是什么?

标签 ruby

从 Net::HTTP 中拯救异常的最佳方法是什么?

抛出的异常在 Ruby 的 socket.c 中有描述。 , 比如 Errno::ETIMEDOUT , Errno::ECONNRESET , 和 Errno::ECONNREFUSED .所有这些的基类是 SystemCallError , 但写出如下代码感觉很奇怪,因为 SystemCallError似乎距离制作 HTTP 还很遥远调用:

begin
  response = Net::HTTP.get_response(uri)
  response.code == "200"
rescue SystemCallError
  false
end

只有我吗?除了修复 Net::HTTP 之外,还有更好的方法来处理这个问题吗?处理 Errno可能会弹出的异常并将它们封装在父级中 HttpRequestException

最佳答案

我同意处理所有潜在的异常绝对是一件痛苦的事情。看this看一个例子:

Working with Net::HTTP can be a pain. It's got about 40 different ways to do any one task, and about 50 exceptions it can throw.

Just for the love of google, here's what I've got for the "right way" of catching any exception that Net::HTTP can throw at you:

begin
  response = Net::HTTP.post_form(...) # or any Net::HTTP call
rescue Timeout::Error, Errno::EINVAL, Errno::ECONNRESET, EOFError,
       Net::HTTPBadResponse, Net::HTTPHeaderSyntaxError, Net::ProtocolError => e
  ...
end

Why not just rescue Exception => e? That's a bad habit to get into, as it hides any problems in your actual code (like SyntaxErrors, whiny nils, etc). Of course, this would all be much easier if the possible errors had a common ancestor.

The issues I've been seeing in dealing with Net::HTTP have made me wonder if it wouldn't be worth it to write a new HTTP client library. One that was easier to mock out in tests, and didn't have all these ugly little facets.

我所做的,并且看到大多数人所做的,是从 Net::HTTP 转移到第 3 方 HTTP 库,例如:

httpartyfaraday

关于ruby - 处理来自 Net::HTTP 的异常的最佳方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5370697/

相关文章:

ruby-on-rails - Ruby On Rails 功能测试 :index with a polymorphic model

ruby-on-rails - Rails 中带有 text_field 的逗号分隔数组

ruby-on-rails - 如何返回单词的状语形式

ruby-on-rails - 如何使用 RSpec 模拟消息链?

ruby - 为什么 `' aeeee'.gsub(/(ae)*/, 'r' )` result in ` "rrerer"`?

ruby - 如何将我的 GVim 设置为 IDE?

ruby - ruby 是否使用堆栈进行内存管理?

ruby - "rhc setup"抛出以下错误

sql - Rails 动态 'Where' 子句

ruby-on-rails - Rails 升级未定义方法 `cookie_verifier_secret`