我有一个连接管理器,其工作方式如下:
def connect(self):
if len(connections) >= max_connections:
raise RuntimeError("Cannot initiate new connection.")
在这种情况下,RuntimeError
是正确的错误吗?或者哪种方法更好?
答案 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))