我有一些代码需要在ruby中拯救多种类型的异常:
begin
a = rand
if a > 0.5
raise FooException
else
raise BarException
end
rescue FooException, BarException
puts "rescued!"
end
Run Code Online (Sandbox Code Playgroud)
我想做的是以某种方式存储我想要在某处救援的异常类型列表,并将这些类型传递给rescue子句:
EXCEPTIONS = [FooException, BarException]
Run Code Online (Sandbox Code Playgroud)
然后:
rescue EXCEPTIONS
Run Code Online (Sandbox Code Playgroud)
这是否可能,并且可能没有一些真正的黑客调用eval?鉴于我在TypeError: class or module required for rescue clause尝试上述内容时所看到的情况,我并不抱希望.
从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
Run Code Online (Sandbox Code Playgroud)
只有我吗?除了修复Net::HTTP以处理Errno可能弹出并将其封装在父级中的异常之外,是否有更好的方法来处理此问题HttpRequestException?