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