Python – How to catch exceptions for a function that is passed as a parameter to another function

How to catch exceptions for a function that is passed as a parameter to another function… here is a solution to the problem.

How to catch exceptions for a function that is passed as a parameter to another function

I have a library that calls the API.

Due to some limitations of the API I’m calling, I’d like to be able to retry the call with different credentials.

Everything in the function I passed the library function to is included.

However, when I tried to catch any exception from the call, nothing was caught, I just ended with a code exit and a stack trace.

The code is shown below

import the_library

def making_the_call(api_call):
    try:
        api_call()
    except TheKeyExceptionIamLookingFor:
        # change creds and redo the call
    except OtherExceptionsICareAboutAndExpect:
        # Do other stuff to handle

making_the_call(the_library.some_api_call(the_args))

This is running in AWS Lambda, so I don’t know if this is the cause of this issue.

I

ran similar code in the python console that caught the exception from the transfer function with parameters, but this code just exits and gives me a stack trace and even shows the exact exception I’m looking for and planning to catch.

Solution

To pass everything individually, you do

def make_call(api_call, *args, **kwargs):
    try:
        return api_call(*args, **kwargs)
    except SomeException:
        # change args and kwargs
        return make_call(api_call, *args, **kwargs)

make_call(the_library.some_api_call, 'apple', 1, 2, 3)

Note that () is missing after some_api_call. In make_call, args will be a list and kwargs (keyword argument) will be a dict

Related Problems and Solutions