错误传播
如果你想传播异常,你可以使用 use from 子句
所有信息都可以在这里查看https://docs.python.org/3/reference/simple_stmts.html#grammar-token-raise-stmt
def c(x, y):
try:
return int(x), int(y)
except Exception as e:
msg = "x or y is probably not a number"
raise Exception(msg) from e
def b(x, y):
try:
x, y = c(x, y)
return x + y
except Exception as e:
msg = "issue during sum of x and y"
raise Exception(msg) from e
def a(x, y):
try:
return b(x, y)
except Exception as e:
msg = "some unknown error occured"
raise Exception(msg) from e
result = a('test', 10)
这样您就可以一直追踪所有错误及其来源
这是输出:
https://i.stack.imgur.com/2ho5K.png
回溯抑制
如果你想抑制你需要使用的错误的所有回溯
from None
def a(x, y):
try:
return b(x, y)
except Exception as e:
msg = "some unknown error occured"
raise Exception(msg) from None
现在运行代码将抑制所有以前的错误,这是输出:
https://i.stack.imgur.com/loFis.png
将错误恢复为字符串
到目前为止,捕获我发现的错误的最佳方法,感谢@anton 的 cmets,他建议使用 traceback 是使用装饰器
from functools import wraps, partial
import traceback
import sys
def error_handler(func=None, *, raise_error=False):
if not func:
return partial(error_handler, raise_error=raise_error)
@wraps(func)
def func_exectutor(*args, **kwargs):
try:
out = func(*args, **kwargs)
exception = False
except Exception as error:
exception = True
string = ''.join(traceback.format_exception(None, error, error.__traceback__))
out = string, error
finally:
if not exception:
return out
else:
if raise_error:
raise out[1]
else:
return out[0]
return func_exectutor
装饰功能后:
@error_handler(raise_error=False)
def a(x, y):
try:
return b(x, y)
except Exception as e:
msg = "some unknown error occured"
raise Exception(msg) from e
如果失败,该函数的输出是一个字符串,其中包含所有可能发生的错误的回溯。如果不是,则输出是预期的
a(4, 10)
>>> 14
a('test', 10)
>>> 'Traceback (most recent call last):
File "/tmp/ipykernel_60630/2959315277.py", line 3, in c
return int(x), int(y)
ValueError: invalid literal for int() with base 10: 'test'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/tmp/ipykernel_60630/2959315277.py", line 10, in b
x, y = c(x, y)
File "/tmp/ipykernel_60630/2959315277.py", line 6, in c
raise Exception(msg) from e
Exception: x or y is probably not a number
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/tmp/ipykernel_60630/2959315277.py", line 19, in a
return b(x, y)
File "/tmp/ipykernel_60630/2959315277.py", line 14, in b
raise Exception(msg) from e
Exception: issue during sum of x and y
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/tmp/ipykernel_60630/879165569.py", line 13, in func_exectutor
out = func(*args, **kwargs)
File "/tmp/ipykernel_60630/2959315277.py", line 22, in a
raise Exception(msg) from e
Exception: some unknown error occured
'