Classifying exceptions

There are many places in my code that need to catch any error generated
by a network system call, but I don't want to catch everything that
inherits from SystemCallError. This is my current code:

ALL_NETWORK_ERRORS = [Errno::ECONNRESET, Errno::ECONNABORTED,
  Errno::ECONNREFUSED, Errno::EPIPE, IOError, Errno::ETIMEDOUT]

ALL_NETWORK_ERRORS << Errno::EPROTO if defined?(Errno::EPROTO)
  # this doesn't exist on mswin32

begin
  raise Errno::ECONNREFUSED
rescue *ALL_NETWORK_ERRORS
  puts "OK!"
end

Now, here's another option, but is there anything wrong with it?

module NetworkRaisable; end
class Errno::EPROTO; include NetworkRaisable; end
class Errno::ECONNREFUSED; include NetworkRaisable; end
# and so on

begin
  raise Errno::ECONNREFUSED
rescue NetworkRaisable
  puts "OK!"
end

···

--
      vjoel : Joel VanderWerf : path berkeley edu : 510 665 3407

Hi,

At Thu, 15 Sep 2005 14:57:22 +0900,
Joel VanderWerf wrote in [ruby-talk:156196]:

Now, here's another option, but is there anything wrong with it?

module NetworkRaisable; end
class Errno::EPROTO; include NetworkRaisable; end
class Errno::ECONNREFUSED; include NetworkRaisable; end
# and so on

begin
  raise Errno::ECONNREFUSED
rescue NetworkRaisable
  puts "OK!"
end

Actually, an exception, to be caught, doesn't have to be
including target module always.

  module NetworkRaisable
    def self.===(ex)
      case ex
      when Errno::EPROTO, Errno::ECONNREFUSED: true
      end
    end
  end

···

--
Nobu Nakada

nobuyoshi nakada wrote:

Hi,

At Thu, 15 Sep 2005 14:57:22 +0900,
Joel VanderWerf wrote in [ruby-talk:156196]:

Now, here's another option, but is there anything wrong with it?

module NetworkRaisable; end
class Errno::EPROTO; include NetworkRaisable; end
class Errno::ECONNREFUSED; include NetworkRaisable; end
# and so on

begin
raise Errno::ECONNREFUSED
rescue NetworkRaisable
puts "OK!"
end

Actually, an exception, to be caught, doesn't have to be
including target module always.

  module NetworkRaisable
    def self.===(ex)
      case ex
      when Errno::EPROTO, Errno::ECONNREFUSED: true
      end
    end
  end

Thanks, that's better. I forgot rescue uses case-matching. And it avoids
modifying ruby built-in classes. (And NetworkRaisable doesn't even have
to be a module.)

···

--
      vjoel : Joel VanderWerf : path berkeley edu : 510 665 3407

Hi,

At Fri, 16 Sep 2005 01:31:37 +0900,
Joel VanderWerf wrote in [ruby-talk:156280]:

Thanks, that's better. I forgot rescue uses case-matching. And it avoids
modifying ruby built-in classes. (And NetworkRaisable doesn't even have
to be a module.)

Arguments to rescue must be modules.

···

--
Nobu Nakada