【发布时间】:2018-12-07 14:31:22
【问题描述】:
我一直想知道抛出异常后谁来控制程序。我正在寻找一个明确的答案,但没有找到任何答案。我描述了以下函数,每个函数都执行一个涉及网络请求的 API 调用,因此我需要通过 try/except 和可能的 else 块处理任何可能的错误(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__": 之后的块),我的意思是,我不想用混乱的 try/catch 块、日志记录等填充它。
当任何这些函数发生异常时,我尝试调用函数本身,但后来我读到堆栈限制并认为这是一个坏主意,应该有更好的方法来处理这个问题。
request在我调用get方法的时候已经自己重试了N次,其中N在源码中是一个常数,是100。但是当重试次数达到0时会抛出错误I需要抓住。
我应该在哪里解码 JSON 响应?在每个函数内部并被另一个 try/catch/else 块包裹?还是在主街区?如何从异常中恢复并继续尝试失败的功能?
任何建议将不胜感激。
【问题讨论】:
-
我不确定您所说的“谁”是什么意思?您对这个问题有哪些设想?
-
@roganjosh 它指的是主执行块(在
if __name__...之后)或通过再次调用自身来抛出异常的同一函数。
标签: python exception python-requests