在我的程序中,我有一个处理requests
调用的函数,并返回处理的调用或引发异常。这个函数被许多其他函数使用,但是我遇到的问题是如何处理可能会引发的异常。目前,它是建立像这样(简化):Python:有没有办法强制父函数返回?
def getFromAPI(url):
# create variable headers
r = requests.get(url, headers=headers)
if r.status_code == 404:
raise Exception("Error raised")
else:
#process data
return data
def functionone():
...
try:
data = getFromAPI(url)
except Exception as e:
return handleException(e)
#handles problems, returns exception-formatted data
...
# formatting data specific to functionone
return formatted_data
def functiontwo():
...
try:
data = getFromAPI(url)
except Exception as e:
return handleException(e)
#handles problems, returns exception-formatted data
...
# formatting data specific to functiontwo
return formatted_data
def functionthree():
...
#similar to functionone and functiontwo
虽然我不认为这是错误的本身,因为getFromAPI
在如此多的功能使用,不必不断地重复尝试,除了陈述感觉错,好像它应该在功能getFromAPI
内处理。但是,由于其他functionone
到function_n
都会根据是否出现错误返回不同的内容,因此我无法在getFromAPI
之内找到处理该问题的方法,除非有办法让getFromAPI
强制它的父函数返回,而没有显式调用父函数中的返回值。
失败了,有没有更好的实现我想要做的,或者我注定要不断重复try语句除外?
让它大声地失败并进一步捕捉它......不处理每个函数中的问题 – 2015-04-02 17:47:31
不幸的是,我没有进一步控制功能。 – echolocation 2015-04-02 17:50:51
“进一步”确实意味着'functionone'..''functionthree'的调用者?或者'getFromAPI'的直接调用者? – kdopen 2015-04-02 17:55:05