views:

44

answers:

1

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
+1  A: 

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

Chubas
Yeah, weird. 1 === 1 => true. Array === Array => false.
Nakilon
Uh. I'd bet `Array === Class` would give true, but now I'm confused. Thanks to your comment now I can't sleep :/
Chubas
Of course, now it makes sense. The `===` is called on the element you're comparing to. So `Class === Array`, `String === "foobar"` and `/foo/ === "foobar"` all return true.
Chubas