我有在多个地方复制粘贴的异常处理代码,例如
def get(self, id):
try:
response = self.client_module_property.get(id)
except APIItemNotFoundException:
print("'{}' does not exist.".format(id), file=sys.stderr)
sys.exit(1)
except Exception as e:
print(
"Unknown error. To debug run with env var LOG_LEVEL=DEBUG",
file=sys.stderr,
)
_log.error(e)
sys.exit(1)
...
而且。。。
def delete(self, id):
try:
self.client_module_property.delete(id=id)
except APIItemNotFoundException:
print("'{}' does not exist".format(id), file=sys.stderr)
sys.exit(1)
except Exception as e:
print(
"Unknown error. To debug run with env var LOG_LEVEL=DEBUG",
file=sys.stderr,
)
_log.error(e)
sys.exit(1)
我已经研究了decorator,但它们对我来说不是一个好的选择,因为我正在内省其他代码中的函数参数,decorator会更改方法签名。
有没有其他方法可以提取可重用的异常处理代码?
这个问题中的注释表明上下文管理器可以在这里使用,但我不清楚浏览python文档会是什么样子。
该解决方案需要在Python 2.7和3.x 上运行
最后,我用wrpt完成了这项工作。我会发布我的解决方案,以防对其他人有用。
最后,只要我能得到方法参数,就可以重用decorator。
我的装饰师:
@wrapt.decorator
def intercept_exception(wrapped, instance, args, kwargs):
"""Handle Exceptions."""
try:
return wrapped(*args, **kwargs)
except AssertionError as ae:
print(ae, file=sys.stderr)
sys.exit(1)
except (
APIException,
APIItemNotFoundException,
ContainerPlatformClientException,
) as e:
print(e.message, file=sys.stderr)
sys.exit(1)
except Exception as ge:
print(
"Unknown error. To debug run with env var LOG_LEVEL=DEBUG",
file=sys.stderr,
)
_log.error(ge)
sys.exit(1)
装饰功能:
@intercept_exception
def get(self, id):
response = self.client_module_property.get(id)
...
我的客户端代码需要检索方法参数
def get_metadata(self):
...
if six.PY2:
parameter_names = list(inspect.getargspec(function).args)
else:
parameter_names = list(
inspect.getfullargspec(function).args
)
...