gpt4 book ai didi

python - 发生异常后谁/如何获得程序的控制权

转载 作者:太空宇宙 更新时间:2023-11-03 21:28:47 25 4
gpt4 key购买 nike

我一直想知道在抛出异常后谁接管了程序的控制权。我一直在寻找明确的答案,但没有找到。我描述了以下函数,每个函数都执行一个涉及网络请求的 API 调用,因此我需要通过 try/except 和可能的 else block 来处理任何可能的错误(JSON 响应也必须被解析/解码):

# This function runs first, if this fails, none of the other functions will run. Should return a JSON.
def get_summary():
pass

# Gets executed after get_summary. Should return a string.
def get_block_hash():
pass

# Gets executed after get_block_hash. Should return a JSON.
def get_block():
pass

# Gets executed after get_block. Should return a JSON.
def get_raw_transaction():
pass

我希望在每个函数上实现一种重试功能,因此如果由于超时错误、连接错误、JSON 解码错误等而失败,它将继续重试,而不会影响程序流程:

def get_summary():
try:
response = request.get(API_URL_SUMMARY)
except requests.exceptions.RequestException as error:
logging.warning("...")
#
else:
# Once response has been received, JSON should be
# decoded here wrapped in a try/catch/else
# or outside of this block?
return response.text

def get_block_hash():
try:
response = request.get(API_URL + "...")
except requests.exceptions.RequestException as error:
logging.warning("...")
#
else:
return response.text

def get_block():
try:
response = request.get(API_URL + "...")
except requests.exceptions.RequestException as error:
logging.warning("...")
#
else:
#
#
#
return response.text

def get_raw_transaction():
try:
response = request.get(API_URL + "...")
except requests.exceptions.RequestException as error:
logging.warning("...")
#
else:
#
#
#
return response.text

if __name__ == "__main__":
# summary = get_summary()
# block_hash = get_block_hash()
# block = get_block()
# raw_transaction = get_raw_transaction()
# ...

我想在它的最外层部分保持干净的代码(if __name__ == "__main__":之后的 block ),我的意思是,我不想用充满困惑的内容填充它try/catch block 、日志记录等

当任何一个函数抛出异常时,我尝试调用函数本身,但后来我读到了有关堆栈限制的内容,并认为这是一个坏主意,应该有更好的方法来处理这个问题。

request 当我调用 get 方法时,它自己已经重试了 N 次,其中 N 在源码中是一个常量,它是 100。但是当重试次数已经达到 0 时,会抛出一个我需要捕获的错误。

我应该在哪里解码 JSON 响应?在每个函数内部并由另一个 try/catch/else block 包裹?或者在主 block ?如何从异常中恢复并继续尝试失败的功能?

如有任何建议,我们将不胜感激。

最佳答案

您可以将它们保持在无限循环中(以避免递归),一旦获得预期响应,只需返回:

def get_summary():
while True:
try:
response = request.get(API_URL_SUMMARY)
except requests.exceptions.RequestException as error:
logging.warning("...")
#
else:
# As winklerrr points out, try to return the transformed data as soon
# as possible, so you should be decoding JSON response here.
try:
json_response = json.loads(response)
except ValueError as error: # ValueError will catch any error when decoding response
logging.warning(error)
else:
return json_response

此函数将持续执行,直到收到预期结果(达到返回 json_response),否则它将一次又一次地尝试。

关于python - 发生异常后谁/如何获得程序的控制权,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53671563/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com