我目前正在编写一个包装器类。我希望能够正确地记录异常,但允许调用方法知道发生的异常。我的类看起来像这样:
import logging
log = logging.getLogger('module')
class MyAPIWrapper(library.APIClass):
def __init__(self):
self.log = logging.getLogger('module.myapiwrapper')
def my_wrapper_method(self):
try:
response = self.call_api_method()
return response.someData
except APIException, e:
self.log.exception('Oh noes!')
raise e #Throw exception again so calling code knows it happened
我有点怀疑捕获和异常只是为了记录它,然后重新引发它,这样调用代码就可以对它做一些事情。这里的正确模式是什么?
发布于 2011-08-10 05:16:23
捕获到日志并没有什么问题。然而,我建议:
try:
response = self.call_api_method()
except APIException, e: # or 'as e' depending on your Python version
self.log.exception('Oh noes!')
raise #Throw exception again so calling code knows it happened
else:
return response.someData
只需执行一个空的raise
,您就可以保留完整的回溯信息。将只有在else
子句中没有异常时才会发生的代码放入代码中也更明确,而且从哪一行捕获异常也更清楚。
如果调用类正在处理错误,那么它也可以做日志记录,但这对你的应用程序来说可能不方便。
编辑:try ... except ... else ... finally
的文档在compound statements下。
https://stackoverflow.com/questions/7003034
复制相似问题