为达到最大连接限制而提出的建议异常类型

时间:2019-10-14 23:47:29

标签: python exception

我有一个连接管理器,其工作方式如下:

def connect(self):
    if len(connections) >= max_connections:
        raise RuntimeError("Cannot initiate new connection.")

在这种情况下,RuntimeError是正确的错误吗?或者哪种方法更好?

1 个答案:

答案 0 :(得分:3)

我认为您可以使用ConnectionError处理与连接问题有关的错误。
在您的情况下,您正在寻找类似 MaxConnectionLimitReachedError 的东西,您可以按如下方式从ConnectionError继承它。

class MaxConnectionLimitReachedError(ConnectionError):
    """
    Exception raised for errors occurring from maximum number 
    of connections limit being reached/exceeded.

    Attributes:
        message -- explanation of the error
        total_connections -- total number of connections when the error occurred (optional)
        max_connections -- maximum number of connections allowed (optional)
    """

    def __init__(self, message, total_connections = None, max_connections = None):
        self.total_connections = total_connections
        self.max_connections = max_connections
        self.message = message
  

您的用例将如下所示

def connect(self):
    if len(connections) >= max_connections:
        message = "Maximum connection limit ({}) reached. Cannot initiate new connection."
        raise MaxConnectionLimitReachedError(message.format(max_connections))
相关问题