gpt4 book ai didi

python - 具有功能的自定义异常

转载 作者:行者123 更新时间:2023-12-01 01:27:00 26 4
gpt4 key购买 nike

我遇到了一个非常标准的问题,想知道我的解决方案是否是正确的方法。

每次发生异常时,我希望调用者能够捕获并记录它,然后重新引发。

由于我不想每次都重复记录消息,因此我创建了一个自定义异常来保存消息数据和日志。

class LoggingException(Exception):
def __init__(self, message, package_id):
# Get caller informat
caller = getframeinfo(stack()[2][0])
self.filename = caller.filename
self.function = caller.function

# Set message info and log
self.message = message
if (LogManager.log_handler is None):
print(message)
else:
LogManager.l(package_id, LogLevelEnum.ERROR, message)

用例:

def main_func():
try:
secondary_func()
except Exception as ex:
raise LoggingException("Some log") from ex

def secondary_func():
raise LoggingException("Exception info")

问题是我不完全确定在任何操作中出现异常是一个好主意,并且这是通用的,因为它没有标准的 python 解决方案。

注意:由于产品限制,我没有使用 python 日志记录模块。

最佳答案

尝试获取这样的调用者信息是不可靠的。此外,在某些情况下,您感兴趣的不是直接调用者。

异常日志记录本身的想法似乎是明智的。为了妥协,我会将日志记录功能移至一个可以显式触发的单独方法中。毕竟,异常(exception)大多是常规对象:

class LoggingException(Exception):
def __init__(self, message, package_id):
# Set message info
super.__init__(message)
self.package_id = package_id

def log(self, manager=None):
if manager.log_handler is None:
print(super().__str__())
else:
manager.l(self.package_id, LogLevelEnum.ERROR, super()..__str__())

现在您可以随时触发日志记录操作,而无需重建消息:

try:
...
except LoggingException as e:
e.log(some_manager)
raise

这使您可以选择真正重新引发错误,如此处所示,或如示例中所示链接它。我强烈建议不要使用链接,除非你有充分的理由这样做。

关于python - 具有功能的自定义异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53247531/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com