I wrote a decorator to avoid having exceptions crash my script and it's not working. Here's the wrapper:
helpers.py
validate_url.py
Why is the script crashing despite my error-checking, which is intended to print a nice error message while not crashing the script?
helpers.py
def try_wrapper(func): """Wrapper that handles exceptions gracefully. :returns: Wrapped function return value (if no error) or None (if error) """ def try_wrap(*args): try: return func(*args) return output except Exception as inst: print(inst) return try_wrapAnd the script so far:
validate_url.py
"""Does some basic validation of provided url :split_url: Helper function using urllib.parse.urlsplit :validate_scheme: Does basic validation of url scheme """ import urllib.parse from helpers import try_wrapper """ Module constants. :schemes: uri scheeas for validation """ schemes = ["https", "http", "ftp"] """Validation and helper functions. """ @try_wrapper def split_url(url): """Splits url for other validation functions. :returns: urllib.split.urlsplit object """ return urllib.parse.urlsplit(url) @try_wrapper def validate_scheme(split_url): """Validates schema of url against a limited list of valid schemas. """ if split_url.scheme in schemes: return split_url else: print("Invalid url scheme {}, must be one of {}".format(split_url.scheme, schemes)) """Testing code to be deleted later. """ while True: url = input("Enter url: ") split = split_url(url) print(split) split_url = validate_scheme(split) print(split)And here's the output I'm getting:
Quote:Enter url: https://bla.bla.com
SplitResult(scheme='https', netloc='bla.bla.com', path='', query='', fragment='')
SplitResult(scheme='https', netloc='bla.bla.com', path='', query='', fragment='')
Enter url: crud://www.bla.com
SplitResult(scheme='crud', netloc='www.bla.com', path='', query='', fragment='')
Invalid url scheme crud, must be one of ['https', 'http', 'ftp']
None
Enter url: ftp
SplitResult(scheme='', netloc='', path='ftp', query='', fragment='')
Invalid url scheme , must be one of ['https', 'http', 'ftp']
SplitResult(scheme='', netloc='', path='ftp', query='', fragment='')
Enter url: ftp:/
Traceback (most recent call last):
File "validate_url.py", line 41, in <module>
split = split_url(url)
TypeError: 'NoneType' object is not callable
<script crashes here>
Why is the script crashing despite my error-checking, which is intended to print a nice error message while not crashing the script?