gylaz gylaz - 4 months ago 40
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.

begin
# my code
rescue Errno
# handle exception
end


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

Answer

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(e.class.name.start_with?('Errno::'))
    # do your thing...
end