我有一个具有多个函数的类。这些函数将处理类似类型的异常。我可以拥有一个处理函数并将其分配给函数吗
最后,我希望函数中不应有异常处理,但在异常时,控件应转到该处理函数
Class Foo:
def a():
try:
some_code
except Exception1 as ex:
log error
mark file for error
other housekeeping
return some_status, ex.error
except Exception2 as ex:
log error
mark file for error
other housekeeping
return some_status, ex.error
类似地,其他函数也会有同样的异常。我想在一个单独的方法中处理所有这些异常。只是函数应该将控制权移交给异常处理函数
我可以考虑从包装处理函数调用每个函数。但我觉得这很奇怪
Class Foo:
def process_func(func, *args, **kwargs):
try:
func(*args, **kwargs)
except Exception1 as ex:
log error
mark file for error
other housekeeping
return some_status, ex.error
except Exception2 as ex:
log error
mark file for error
other housekeeping
return some_status, ex.error
def a(*args, **kwargs):
some_code
有更好的方法吗
您可以定义函数装饰器:
并用作:
因此
func(...)
等价于process_func(func)(...)
,错误在wrapped_func
内处理相关问题 更多 >
编程相关推荐