python - 为达到最大连接限制而引发的建议异常类型
问题描述
我有一个连接管理器,其工作方式如下:
def connect(self):
if len(connections) >= max_connections:
raise RuntimeError("Cannot initiate new connection.")
在这种情况下提出一个RuntimeError
正确的错误,或者什么是更好的方法?
解决方案
我认为您可以使用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))
推荐阅读
- reactjs - 传单自定义编辑?处理程序?
- python - Discord.Py 没有在 Discord 中发送我的消息
- haskell - 在 Haskell 中创建一个包含三元组所有可能变体的数组
- logging - 让 Apache Camel 记录被调用的 URL
- python - 我的用户名检查器一直说所有名称都可用,尽管进行了 if/else 测试
- javascript - 使用 mouseX/Y、if 语句和图像在 p5.js 中创建迷宫
- java - 如何使用 Google guava 缓存库单独获取密钥
- php - 操作 for 循环以仅使用特定变量运行代码
- java - 如何获取批处理文件以自动填充 Java 代码提示的输入
- python - “[WinError 10061] 由于目标机器主动拒绝,无法建立连接”