如何从作为参数传递给另一个函数的函数中捕获异常

2024-05-08 22:35:17 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个调用API的库

由于我正在调用的API的某些限制,我希望能够使用不同的凭据重试调用

我拥有库函数传递到的函数中的所有内容

但是,当我试图从调用中捕获任何异常时,都不会捕获任何异常,我只会以代码退出和堆栈跟踪结束

代码如下所示

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))

这是运行在aws lambda,所以我不知道这是什么帮助导致这个问题

我在python控制台中运行了类似的代码,它可以很好地捕获带有参数的传递函数中的异常,但这段代码只是退出,并提供了一个堆栈跟踪,甚至显示了我正在查找和计划捕获的确切异常


Tags: the函数代码importapi内容堆栈def
1条回答
网友
1楼 · 发布于 2024-05-08 22:35:17

把你要做的每件事都分开传递

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)

注意在some_api_call之后缺少()。内部make_callargs将是listkwargs(关键字参数)将是dict

相关问题 更多 >