用Ruby标记异常,一种解释/替代方法
我已经阅读了一个技巧,在您拥有自己的库的情况下标记您自己的异常:用Ruby标记异常,一种解释/替代方法,ruby,exception-handling,Ruby,Exception Handling,我已经阅读了一个技巧,在您拥有自己的库的情况下标记您自己的异常: module AcmeHttp module Error; end end begin begin raise IOError, "Some IO error" rescue Exception => error error.extend(AcmeHttp::Error) raise end rescue AcmeHttp::Error => error puts "Res
module AcmeHttp
module Error; end
end
begin
begin
raise IOError, "Some IO error"
rescue Exception => error
error.extend(AcmeHttp::Error)
raise
end
rescue AcmeHttp::Error => error
puts "Rescued AcmeHttp::Error: #{error}"
end
我不确定error.extend(AcmeHttp::error)
是如何工作的,以及以后如何使用它进行实际救援。另外,是否有更优雅的方法来标记您自己库中的异常?将一个或多个模块的实例方法添加到receiver对象
因此,当您执行
error.extend(AcmeHttp::error)
时,实际上是将AcmeHttp::error
模块的实例方法添加到error
中,这是一个异常(实际上是一个类对象)。extend
是正常的Ruby。原因是为了抓住根本原因。另一种方法是.AcmeHttp::Error为什么与rescue匹配?因为extend
使AcmeHttp::Error
成为Error
的单例类的超类。就像@DaveNewton在他对你的问题的评论中所说的那样,extend
与异常无关,它只是基本的Ruby。@Jörg W Mittag有没有一种方法可以看到这个祖先链,就像你对AnyClass.祖先所做的一样(只是这次,它是针对对象的)?