DEV Community

Vighnesh SK
Vighnesh SK

Posted on

Python Decorators for Error handling

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

Applying 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


Now apply 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 :)

Top comments (1)

Collapse
 
azamatkelemetov profile image
AzamatKelemetov

I registered here just to say thank you. That is an extremely usefull example. Now I don't have to put dozens of lines with exceptions in every function.
many thanks.