Michael Hallabrin
Michael Hallabrin

Reputation: 53

Python Requests Unable to Handle 403 Error

I'm getting a 403 error from a request I'm making (which is fine that's not the issue). However, I can't seem to catch an except and properly handle the error. My code just moves on like nothing went wrong and is causing other issues. Code

    try:
        verify = True if os.environ.get('environment', 'dev') != 'dev' else False
        response = requests.post(url, headers=headers, data=payload, verify=verify)
        return response.content
    except requests.HTTPError as e:
        print('Error', e)
        return None
    except requests.exceptions.RequestException as e:
        print("Connection refused", e)
        return None
    except Exception as e:
        print("Internal error", e)
        return None

Is there something else I can try?

Upvotes: 3

Views: 3470

Answers (1)

Greg
Greg

Reputation: 4518

To capture 403 you need to raise exception. This can be done by calling response.raise_for_status() after the post. see documentation.

try:
    verify = True if os.environ.get('environment', 'dev') != 'dev' else False
    response = requests.post(url, headers=headers, data=payload, verify=verify)
    response.raise_for_status() # This will throw an exception if status is 4xx or 5xx
    return response.content
except requests.HTTPError as e:
    print('Error', e)
    return None
except requests.exceptions.RequestException as e:
    print("Connection refused", e)
    return None
except Exception as e:
    print("Internal error", e)
    return None

Upvotes: 5

Related Questions