首页 > 解决方案 > 引发异常并在上层方法调用中除外

问题描述

我一直在处理我试图改进如何正确提高的例外情况。我做过这样的事情

主文件

from lib.utils import ExceptionCounter

class BarryException():
    pass
    
candy = "hello"
color = "world"

try:
    test = type(int("string"))
except Exception as err:

    # My own counter for exception that sends to discord if allowed_count is 0 by calling discord.notify(msg)
    ExceptionCounter().check(
        exception=BarryException,
        allowed_count=0,
        msg={
            'Title': 'Unexpected Error',
            'Reason': str(err),
            'Payload': str({"candy": candy, "color": color})
        }
    )

lib.utils

class ExceptionCounter:
    """
    Counter to check if we get exceptions x times in a row.
    """

    def __init__(self):
        self.exception_count = {}

    def check(self, exception, msg, allowed_count):
        exception_name = exception.__name__

        # the dict.get() method will return the value from a dict if exists, else it will return the value provided
        self.exception_count[exception_name] = self.exception_count.get(exception_name, 0) + 1

        if self.exception_count[exception_name] >= allowed_count:
            Discord_notify(msg)
            raise exception(msg)

    def reset(self):
        self.exception_count.clear()

然而,来自 Code Review 的人建议我这样做:

在自定义异常类型中使用上下文数据引发:

try:
    ...
except Exception as e:
    raise BarryException('Unexpected error testing', candy=candy, color=color) from e

不要从那里打电话给 Discord;不要在那里进行异常计数;不要在那里形成不和谐的消息有效负载字典 - 只是提高。在上面的方法中,您可以排除并执行 Discord 通知。

ExceptionCounter 根本不应该知道 Discord,并且应该严格限制异常计数限制和重新引发。


我的问题是我不太了解刚刚提出的部分。在上面的方法中,您可以排除并执行 Discord 通知。- 如果有人可以解释甚至向我展示它的实际含义的示例,我将不胜感激:(

标签: python-3.x

解决方案


推荐阅读