Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
674 views
in Technique[技术] by (71.8m points)

ruby - How to catch Errno::ECONNRESET class in "case when"?

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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...