如何在“case when”中捕获Errno :: ECONNRESET类? [英] How to catch Errno::ECONNRESET class in "case when"?

查看:152
本文介绍了如何在“case when”中捕获Errno :: ECONNRESET类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的应用程序(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 
3
/ pre>

解决方案

这是因为 === 类上工作



案例 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 do case/when to handle them in defferent ways, but several errors go through my cases straight to else.

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 class Class

The case statement internally calls the === method on the object you are evaluating against. If you want to test for e class, you just test against e, not e.class. That's because e.class would fall into the when 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类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆