我有一个用于python-mpd2的非常基本的代理类(一个帮助我编写它的朋友坚持认为它是一个装饰类)。在
班级看起来像这样
import mpd
class MPDProxy:
def __init__(self, host="localhost", port=6600, timeout=10):
self.client = mpd.MPDClient()
self.host = host
self.port = port
self.client.timeout = timeout
self.connect(host, port)
def __getattr__(self, name):
return self._call_with_reconnect(getattr(self.client, name))
def connect(self, host, port):
self.client.connect(host, port)
def _call_with_reconnect(self, func):
def wrapper(*args, **kwargs):
try:
return func(*args, **kwargs)
except mpd.ConnectionError:
self.connect(self.host, self.port)
return func(*args, **kwargs)
return wrapper
mpd_proxy = MPDProxy()
到目前为止,只要有一个mpd主机可以连接,这个方法就可以正常工作。如果没有mpd服务器,我可以
ConnectionRefusedError: [Errno 111] Connection refused
我正在寻找处理这个异常的好模式
try ... except
;)你应该扪心自问的问题是:“谁有能力处理这个例外?”
显然,代理不能对任何合理的“修复”
ConnectionRefusedError
。所以必须在高层处理。在坏主意。通知“上层”而不是发生异常的正常方法是
raise
一个异常。或者让引发的异常传播。在具体来说:
相关问题 更多 >
编程相关推荐