首页 > 解决方案 > 为达到最大连接限制而引发的建议异常类型

问题描述

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

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

在这种情况下提出一个RuntimeError正确的错误,或者什么是更好的方法?

标签: pythonexception

解决方案


我认为您可以使用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))

推荐阅读