处理来自 Net::HTTP 的异常的最佳方法是什么? [英] What’s the best way to handle exceptions from Net::HTTP?
问题描述
从 Net::HTTP 中拯救异常的最佳方法是什么?
What’s the best way to rescue exceptions from Net::HTTP?
抛出的异常在 Ruby 的 socket.c
中描述,如 Errno::ETIMEDOUT
、Errno::ECONNRESET
和 Errno::ECONNREFUSED
.所有这些的基类是 SystemCallError
,但编写如下代码感觉很奇怪,因为 SystemCallError
似乎与制作 HTTP
相去甚远> 调用:
Exceptions thrown are described in Ruby’s socket.c
, like Errno::ETIMEDOUT
, Errno::ECONNRESET
, and Errno::ECONNREFUSED
. The base class to all of these is SystemCallError
, but it feels weird to write code like the following because SystemCallError
seems so far removed from making an HTTP
call:
begin
response = Net::HTTP.get_response(uri)
response.code == "200"
rescue SystemCallError
false
end
就我一个人吗?除了修复 Net::HTTP
以处理可能弹出并将它们封装在父 HttpRequestException
中的 Errno
异常之外,是否有更好的方法来处理此问题?代码>?
Is it just me? Is there a better way to handle this beyond fixing Net::HTTP
to handle the Errno
exceptions that would likely pop up and encapsulate them in a parent HttpRequestException
?
推荐答案
我同意处理所有潜在的异常绝对是一件痛苦的事情.查看 this 以查看示例:
I agree it is an absolute pain to handle all the potential exceptions. Look at this to see an example:
使用 Net::HTTP
可能会很痛苦.它有大约 40 种不同的方式执行任何一项任务,它可以抛出大约 50 个异常.
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.
出于对谷歌的热爱,这就是我对正确方式"的理解捕获 Net::HTTP 可能抛出的任何异常:
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
为什么不只是 rescue Exception =>
?这是一个坏习惯,因为它隐藏了您实际代码中的任何问题(例如 SyntaxErrors、whiny零等).当然,如果可能的话,这一切都会容易得多错误有一个共同的祖先.
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.
我在处理 Net::HTTP 时遇到的问题让我想知道是否不值得编写一个新的 HTTP 客户端库.一种在测试中更容易模拟的,并且没有所有这些丑陋的小面.
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 转移到 3rd 方 HTTP 库,例如:
What I've done, and seen most people do, is move away from Net::HTTP and move to 3rd party HTTP libraries such as:
这篇关于处理来自 Net::HTTP 的异常的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!