我们可以在语句之后放置一个类或模块rescue
,但是在下面的代码中,我看到了一个方法rescue
,它不适合这种模式。它是如何工作的,它是如何产生它所设计的输出的?
def errors_with_message(pattern)
# Generate an anonymous "matcher module" with a custom threequals
m = Module.new
(class << m; self; end).instance_eval do
define_method(:===) do |e|
pattern === e.message
end
end
m
end
puts "About to raise"
begin
raise "Timeout while reading from socket"
rescue errors_with_message(/socket/)
puts "Ignoring socket error"
end
puts "Continuing..."
输出
About to raise
Ignoring socket error
Continuing...