So I had a little python script that scraps a certain website for product data. A couple of functions that fetches data, parses for one type of content, another type of data.
Now I had this issue where the css selectors returns None which breaks all my sneaky list indices.
Currently my program looks like this.
def get_x_info(url): # piece of code that works all the time # piece of code that crashes return result
try and except to the piece of code that crashes wasn't quite convincing because of the tedious task of doing this to all of the probable volatile code. And I wasn't quite sure of what part might crash.
Hence, Python Decorators.
A syntactic sugar for wrapping functions with a reusable code.
Learn about it here
Here is how I used decorators error handle the functions that throws errors most of the time.
def safe_run(func): def func_wrapper(*args, **kwargs): try: return func(*args, **kwargs) except Exception as e: print(e) return None return func_wrapper
safe_run as a decorator to the function declarations in the main code
@safe_run def get_x_info(url): ....
Quick terrible fix that works :)