Created
February 16, 2012 05:04
-
-
Save anithri/1842203 to your computer and use it in GitHub Desktop.
Toying with an idea for exception handling.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module MyModule | |
class MyModuleError < StandardError | |
@@ignore = :warn | |
def ok_to_ignore? | |
@@ignore | |
end | |
def self.ok_to_ignore | |
@@ignore | |
end | |
alias ok_to_ignore? ok_to_ignore | |
def self.ok_to_ignore=(val) | |
@@ignore = val | |
end | |
end | |
class ConfigFileError < GridDataError; end | |
module RaiseOrIgnore | |
def raise_or_ignore(*args) | |
if args[0].kind_of?(Exception) && args[0].respond_to(:ignore_me?) && args[0].ignore_me? | |
if args[0].ignore_me? == :silent | |
return nil | |
else | |
warn args.map(&:to_s).join(":") | |
return nil | |
end | |
end | |
raise args | |
end | |
end | |
module Kernel | |
include RaiseOrIgnore | |
end | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def some_method | |
raise_or_ignore MyModuleError, "whoops" | |
end | |
MyModule.ok_to_ignore = :silent | |
some_method #nil | |
MyModule.ok_to_ignore = true | |
some_method #nil | |
#STDERR | |
#MyModuleError whoops | |
MyModule.ok_to_ignore = false | |
some_method | |
#normal exception raised. | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The specific code might not be exactly right yet, I don't want to spend any time on this until I get a better idea of if this is worth pursuing.
But the idea of being able to change some exceptions to just print a warning. or to just fail silently, or to raise an exception, makes my decisions as a gem author easier. I can raise things as warnings most of the time (say an config file is missing), but I can change it to raise the exception if I as a gem consumer decide it should be a show stopper.