问题描述
我的应用程序(Ruby 1.9.2)可能引发不同的异常,包括网络连接中断。我 rescue Exception => e
,然后执行 case / when
以不同的方式处理它们,但是几个错误通过我的案例直到 else
。
rescue Exception => e
p e.class
case e.class
当Errno :: ECONNRESET
p 1
当Errno :: ECONNRESET,Errno :: ECONNABORTED,Errno :: ETIMEDOUT
p 2
else
p 3
end
end
打印:
Errno :: ECONNRESET
/ pre>
3
解决方案这是因为
===
在类上工作
案例
a href =http://ruby-doc.org/core/classes/Object.html#M000345 =noreferrer>内部调用===
方法对您正在评估的对象。如果你想测试e
类,你只需要测试e
而不是e。类
。那就是因为,在Class case时,因为e.class
将落入中,因为e.class是一个Class。
rescue Exception =>当Errno :: ECONNRESET,Errno :: ECONNABORTED,Errno :: ETIMEDOUT
p 2
时,e
case e
当Errno :: ECONNRESET
p 1
p 3
end
end
是的,Ruby可以有奇怪语义有时
My application (Ruby 1.9.2) may raise different exceptions, including net-connection breaks. I
rescue Exception => e
, then docase/when
to handle them in defferent ways, but several errors go through my cases straight toelse
.rescue Exception => e p e.class case e.class when Errno::ECONNRESET p 1 when Errno::ECONNRESET,Errno::ECONNABORTED,Errno::ETIMEDOUT p 2 else p 3 end end
Prints:
Errno::ECONNRESET 3
解决方案This is because of how the
===
operator works on the classClass
The
case
statement internally calls the===
method on the object you are evaluating against. If you want to test fore
class, you just test againste
, note.class
. That's becausee.class
would fall into thewhen Class
case, because, well, e.class is a Class.rescue Exception => e case e when Errno::ECONNRESET p 1 when Errno::ECONNRESET,Errno::ECONNABORTED,Errno::ETIMEDOUT p 2 else p 3 end end
Yeah, Ruby can have weird semantics sometimes
这篇关于如何在“case when”中捕获Errno :: ECONNRESET类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!