[Python] Raising Exceptions if something goes wrong, return a value if function completes...

Discussão em 'Python' iniciado por Stack, Abril 15, 2025.

  1. Stack

    Stack Membro Participativo

    I'm writing an API authentication function and basically I'd like it to do this:

    def authenticate():
    params = {"credential": "xxxx"}
    url = "www.test-api.com/oauth.token"
    response = request.post(url, params)

    if response.status_code == 200:
    token = response.json()
    return token
    else:
    raise RuntimeError("Authentication failed")


    Then, in main():

    try:
    token = authenticate()
    except RuntimeError:
    print("Error")
    else:
    print("good")


    I can see the Runtime Error, but the else block also runs, ie "good" is printed after the traceback. I suspect it is due to authenticate() returning None when the exception is raised. Is it possible/best practice to have something like this? I'd like to keep the exception as I want it for logging purposes.

    Here is my log file:

    2025-04-15 10:19:00 - ERROR - An error has been caught in function '<module>', process 'MainProcess' (2468551), thread 'MainThread' (140286569478016):
    Traceback (most recent call last):

    > File "/testing/Python/Code/test.py", line 35, in <module>
    token = authenticate(
    │ └ <function authenticate at 0x7f96fcc0eac0>
    └ <module 'ShareFile_API' from '/testing/Python/Code/Python/Code/utilities/API.py'>

    File "/testing/Python/Code/utilities/API.py", line 60, in authenticate
    raise RuntimeError(f"API Authentication Error {response.status_code} {response.reason}")

    RuntimeError: ShareFile API Authentication Error 400 Bad Request
    2025-04-15 10:19:00 - INFO - Authentication successful

    Continue reading...

Compartilhe esta Página