gylaz gylaz - 1 year ago 199
Ruby Question

How to rescue all exceptions under a certain namespace?

Is there a way to rescue all exceptions under a certain namespace?

For example, I want to rescue all of the Errno::* exceptions (Errno::ECONNRESET, Errno::ETIMEDOUT). I can go ahead and list them all out on my exception line, but I was wondering if I can do something like.

# my code
rescue Errno
# handle exception

The above idea doesn't seem to work, thus is there something similar that can work?

Answer Source

All the Errno exceptions subclass SystemCallError:

Module Errno is created dynamically to map these operating system errors to Ruby classes, with each error number generating its own subclass of SystemCallError. As the subclass is created in module Errno, its name will start Errno::.

So you could trap SystemCallError and then do a simple name check:

rescue SystemCallError => e
    raise e if('Errno::'))
    # do your thing...
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download