Lets say I have a function:
def ReadFile():
with open("/etc/passwd") as file:
data = file.read()
This function might succeed, in which case it needs to return a result, or it might fail, in which case I want to return a traceback of the exception, which will get emailed to me so I know something failed in my program, and exactly what failed.
To do this, I can do something like:
import traceback
def ReadFile():
try:
with open("/etc/passwd") as file:
data = file.read()
except IOError:
return traceback.format_exc()
return data
If it is able to read the file successfully, it returns the contents of the file. Otherwise, it returns the traceback of the exception.
traceback.format_exc() returns a string. If ReadFile() is supposed to return a list, or tuple or integer if it succeeds, than things are easy - when you call ReadFile(), if the result returned is a string, you know it failed and you can run code that emails you the error, and if the result is the type you expected (int, tuple, list or w/e), than you know it worked.
If ReadFile() is supposed to return a string, as it does in my example, than figuring out if ReadFile() succeeded or failed becomes significantly more difficult, as you need to parse the string to figure out if it looks like a traceback or the result you expected.
Is there a better way to do this? Perhaps some way to have traceback return some sort of object with the same information as traceback.format_exc() contains, so that it's easier to figure out if ReadFile() succeeded or failed?