我想创建一个以function作为参数和元组列表的函数。元组的第一个元素是错误,第二个元素是消息。示例调用:
handle_error(sum, [(ValueError, 'bad value'), (AttributeError, 'attribute error')])此错误应在try/except块中处理。我猜不可能动态定义异常的数量。执行下面伪代码示例中演示的操作的最佳实践是什么?
def handle_error(function, errors):
try:
function()
for error in errors:
except error[0] as e:
print(error[1])我想实现这样的行为,以使我的应用程序中的日志记录更干净。
发布于 2020-09-24 19:25:04
由于Exception%s是可散列的,请使用dict。
from collections.abc import Callable # just for type hinting.
def handle_error(callable_: Callable, error_dict: dict):
try:
callable_()
except Exception as err:
print(error_dict[type(err)])
# Testers
def tester(error_type):
raise error_type()
# Test
handle_error(lambda: tester(ValueError), {ValueError: "bad val", AttributeError: "bad attr"})
handle_error(lambda: tester(AttributeError), {ValueError: "bad val", AttributeError: "bad attr"})bad val
bad attr正如我所看到的,你调用函数时不带参数,我从处理程序中删除了callable的参数。您仍然可以像上面那样使用lambda传递参数,但最好更改处理程序的签名,如下所示:
def handle_error(callable_: Callable, error_dict: dict, *args):
try:
callable_(*args)https://stackoverflow.com/questions/64044939
复制相似问题