Created
February 1, 2020 02:36
-
-
Save Jordan-Cottle/d5d60239e41eb6f0bffd27d0913b76ce to your computer and use it in GitHub Desktop.
A decorator that takes in an exception type and handles it
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
class BaseException(Exception): | |
""" This is a basic exception """ | |
class NotBasicException(BaseException): | |
""" This is not a basic exception """ | |
def args_decorator(ExceptionType, msg, status_code): | |
def decorate(func): | |
print(f'Decorating {func}') | |
def wrapper(*args, **kwargs): | |
try: | |
return func(*args, **kwargs) | |
except ExceptionType as error: | |
print(f'Catching {ExceptionType}') | |
print(error) | |
print(f"Returning {msg}, {status_code}") | |
return msg, status_code | |
return wrapper | |
return decorate | |
@args_decorator(BaseException, 'This was not a basic exception!', 500) | |
def some_endpoint(some_arg): | |
try: | |
b = some_arg + 2 | |
a = some_arg * 2 | |
except TypeError as error: | |
raise NotBasicException(*error.args) | |
return a + b | |
print(some_endpoint(42)) | |
print(some_endpoint('Whee')) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment