reneboer / python-carnet-client

python script that emulated the VW WE Connect (formerly CarNet) web site
GNU General Public License v3.0
21 stars 9 forks source link

Catching exceptions inside functions? #10

Closed birgersp closed 5 years ago

birgersp commented 5 years ago

Hi,

I noticed you're catching exceptions inside functions. Example:

def extract_csrf(string):
    # Get value from HTML head _csrf meta tag.
    try:
        csrf_re = re.compile('<meta name="_csrf" content="(.*?)"/>')
        resp = csrf_re.search(string).group(1)
    except:
        resp = ''
    return resp

Why are you doing this? Exceptions are meant to show the developers exactly where a problem occurs. When you are doing this, you're reducing the error to a single line of text which makes the developer have to dig through the source code to find the source of error.

Also now the script has to check the result of each of the functions, which is unnecessary when you have exceptions interrupting the execution of the script. As shown here:

    landing_page_response = session.get(landing_page_url)
    if landing_page_response.status_code != 200:
        return '', 'Failed getting to portal landing page.'
    csrf = extract_csrf(landing_page_response.text)
    if csrf == '':
        return '', 'Failed to get CSRF from landing page.'

The example function should simply be:

def extract_csrf(string):
    # Get value from HTML head _csrf meta tag.
    csrf_re = re.compile('<meta name="_csrf" content="(.*?)"/>')
    return csrf_re.search(string).group(1)
birgersp commented 5 years ago

Also, when using a proper IDE or code editor, exceptions are properly visualized:

image

reneboer commented 5 years ago

I'm no python expert and this way I try to avoid the code bombs out for often not to clear reasons. Now I can exactly see where an error occurred. For me it is simpler, if you want to do the differently you are free to publish your own version.