Created
May 2, 2012 09:46
-
-
Save japsu/2575597 to your computer and use it in GitHub Desktop.
Wrap exceptions in a custom exception class
This file contains hidden or 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
class errors_wrapped(object): | |
""" | |
A function decorator to wrap all exceptions in an exception class of | |
your choosing. | |
Usage: | |
@errors_wrapped(MyExceptionClass) | |
def my_function(... | |
MyExceptionClass should accept this: | |
... | |
catch Exception, e: | |
raise MyException(e) | |
""" | |
def __init__(self, ecls): | |
self.ecls = ecls | |
def __call__(self, func): | |
@wraps(func) | |
def wrapped(*args, **kwargs): | |
try: | |
return func(*args, **kwargs) | |
except Exception, e: | |
trace = sys.exc_info()[2] | |
raise self.ecls(e), None, trace | |
return wrapped |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment