如何处理代理类中的不可用主机(ConnectionRefusedError)

2024-10-04 05:22:31 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个用于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

我正在寻找处理这个异常的好模式

  • 当没有主机可用时,您能想出一种优雅的方法来防止程序崩溃吗?在
  • 无论何时调用代理,我应该在代理内部还是外部捕获异常?在
  • 字符串“hostnotavailable”(或类似的)作为返回值是个好主意,还是可以以更好的方式通知调用代理的方法/函数?在

Tags: 方法selfclienthost代理returnportdef
1条回答
网友
1楼 · 发布于 2024-10-04 05:22:31

Can you think of an elegant way to prevent the program to crash, when there is no host available?

try ... except;)


Should I catch the exception within the proxy or outside, whenever the proxy is called?

你应该扪心自问的问题是:“谁有能力处理这个例外?”


显然,代理不能对任何合理的“修复”ConnectionRefusedError。所以必须在高层处理。在


Is a string "Host not available" (or similar) as a return value a good idea or can a method/function calling the proxy be informed in a better way?

坏主意。通知“上层”而不是发生异常的正常方法是raise一个异常。或者让引发的异常传播。在


具体来说:

class MPDProxy:
    def _call_with_reconnect(self, func):
        def wrapper(*args, **kwargs):
            try:
                return func(*args, **kwargs)
            except mpd.ConnectionError:
                self.connect(self.host, self.port)
                # ^^^^^^ This lime might raise `ConnectionRefusedError`
                # as there is no `except` block around, this exception
                # is automatically propagated     

                return func(*args, **kwargs)
        return wrapper

try:
    mpd_proxy = MPDProxy()
    r = mdp_proxy._call_with_reconnect(whatever)
except ConnectionRefusedError:
    do_somesible_sensible()

相关问题 更多 >